top of page

Upserting Records

This example uses upsert and an external ID field Line_Item_Id__c on the Asset object to maintain a one-to-one relationship between an asset and an opportunity line item.


Before running this sample, create a custom text field on the Asset object named Line_Item_Id__c and mark it as an external ID. For information on custom fields, see the Salesforce online help.

public void upsertExample() {

Opportunity opp = [SELECT Id, Name, AccountId,

(SELECT Id, PricebookEntry.Product2Id, PricebookEntry.Name

FROM OpportunityLineItems)

FROM Opportunity

WHERE HasOpportunityLineItem = true

LIMIT 1];


Asset[] assets = new Asset[]{};


// Create an asset for each line item on the opportunity

for (OpportunityLineItem lineItem:opp.OpportunityLineItems) {


//This code populates the line item Id, AccountId, and Product2Id for each asset

Asset asset = new Asset(Name = lineItem.PricebookEntry.Name,

Line_Item_ID__c = lineItem.Id,

AccountId = opp.AccountId,

Product2Id = lineItem.PricebookEntry.Product2Id);


assets.add(asset);

}

try {

upsert assets Line_Item_ID__c; // This line upserts the assets list with

// the Line_Item_Id__c field specified as the

// Asset field that should be used for matching

// the record that should be upserted.

} catch (DmlException e) {

System.debug(e.getMessage());

}

}


Recent Posts

See All
Using Joins in SOQL

Semi-Joins with IN: Eg, query using objects - Account and Opportunity, SELECT Id, Name FROM Account WHERE Id IN ( SELECT AccountId FROM...

 
 
 
Data Quality Management

To return duplicate Account/Contact/Lead names: select name, count(id) from <Account/Contact/Lead> group by name having count(id) > 1 To...

 
 
 

Comments


Post: Blog2_Post

©2020 by SalesforceDemystified. Proudly created with Wix.com

bottom of page