I am creating a visualforce page and a custom apex class for a page that allows users to convert opportunities and opportunity line items into service contracts and contract line items.
I've got all the field data into the places I want it, and am at the point where I upsert the the new service contract, but I can't think how to add the contract line items. I suppose I need the service contract's Id, but I would've assumed I can't do that in the code here because I have no way of knowing what Id I am querying for. Can someone clarify the way of doing this? Here is the code I have so far for reference, any other problems you can see let me know too as I'm still learning.
global class ContractCreationController
{
final Opportunity opp;
final List<OpportunityLineItem> lineItems;
ServiceContract sc;
List<ContractLineItem> contractItems;
public ContractCreationController()
{
opp = [SELECT Id,
OwnerId,
Name,
AccountId,
Account.Name,
Primary_Contact__c,
Account.BillingStreet,
Account.BillingCity,
Account.BillingState,
Account.BillingPostalCode,
Account.BillingCountry
FROM Opportunity WHERE Id = :ApexPages.currentPage().getParameters().get('oid')];
lineItems = [SELECT Id,
Discount,
Description,
PricebookEntryId,
PricebookEntry.Name,
Quantity,
UnitPrice
FROM OpportunityLineItem WHERE OpportunityId = :opp.Id];
sc = new ServiceContract();
sc.AccountId = opp.Id;
sc.OwnerId = opp.OwnerId;
sc.Name = opp.Account.Name + ' - ' + opp.Name;
sc.ContactId = opp.Primary_Contact__c;
sc.BillingStreet = opp.Account.BillingStreet;
sc.BillingCity = opp.Account.BillingCity;
sc.BillingState = opp.Account.BillingState;
sc.BillingCountry = opp.Account.BillingCountry;
sc.BillingPostalCode = opp.Account.BillingPostalCode;
contractItems = new List<ContractLineItem>();
for (OpportunityLineItem items : lineItems)
{
ContractLineItem cli = new ContractLineItem();
cli.Discount = items.Discount;
cli.Description = items.Description;
cli.PricebookEntryId = items.PricebookEntryId;
cli.Quantity = items.Quantity;
cli.UnitPrice = items.UnitPrice;
contractItems.add(cli);
}
}
public PageReference save()
{
try
{
upsert(sc);
//Not quite sure how to upsert all my contract line items :S
}
catch (System.DMLException e)
{
ApexPages.addMessages(e);
return null;
}
return (new ApexPages.StandardController(sc)).view();
}
}