2

I'm upserting a list of custom objects in an Apex controller that are retrieved on demand from an external source. My object has an external identifier field used to help the database call determine if the indiviudual objects needs to be inserted/updated.

Basically, after the upsert, I would like to know which of these objects have been inserted, and which have been updated. Is this possible? I see in external API integrations you have access to the UpsertResult class, which has an attribute isCreated(), which tells you exactly this, but I can't see any way to get this from directly inside Apex.

I know I could do a SOQL interrogation of the objects before the upsert, just curious to see if I could get this information directly from the DML call.

Any suggestions?

2

The UpsertResult data is available if you use the Database.upsert method rather than the upsert keyword.

From Upserting Records:

/* This class demonstrates and tests the use of the
 * partial processing DML operations */ 

public class DmlSamples {

   /* This method accepts a collection of lead records and 
      creates a task for the owner(s) of any leads that were 
      created as new, that is, not updated as a result of the upsert
      operation */
   public static List<Database.upsertResult> upsertLeads(List<Lead> leads)  {

      /* Perform the upsert. In this case the unique identifier for the
         insert or update decision is the Salesforce record ID. If the 
         record ID is null the row will be inserted, otherwise an update
         will be attempted. */
      List<Database.upsertResult> uResults = Database.upsert(leads,false);

      /* This is the list for new tasks that will be inserted when new 
         leads are created. */
      List<Task> tasks = new List<Task>();
      for(Database.upsertResult result:uResults) {
         if (result.isSuccess() && result.isCreated()) 
              tasks.add(new Task(Subject = 'Follow-up', WhoId = result.getId()));
      }

      /* If there are tasks to be inserted, insert them */
      Database.insert(tasks);

      return uResults;
   }
}
1
  • Fantastic! Thanks for that Keith, for some reason I thought the Database.Upsert method was only available through API calls slaps head. Nov 18 '14 at 12:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.