function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Dman100Dman100 

identity equivalent

Is there an apex equivalent of getting the id of a newly inserted record?

 

trigger InsertCaseContact on Case (before update) { //Create a new list for caseIds List<Id> caseIds = new List<Id>{}; //Loop through the Cases we're adding and build a list of Ids for(Case cas: Trigger.new) caseIds.add(cas.Id); List<Contact> addContacts = new List<Contact>(); // Loop through the Trigger.new array of Cases. for(Case cas:Trigger.new){ if (cas.SuppliedName != null) { addContacts.add(new Contact (LastName = cas.SuppliedName, Email = cas.SuppliedEmail, Phone = cas.SuppliedPhone)); } } insert addContacts; }

 

I'd like to get the id of the newly inserted contact records.
BritishBoyinDCBritishBoyinDC

addContacts is a list...so if you do a for loop on the list after the insert, you can get the Id of the new contacts

 

 

Dman100Dman100

I created a set of ids and looped thru the list, which is now populated with the contact ids.  I want to update the cases and set the case Contact lookup field with the contact ids.

 

trigger InsertCaseContact on Case (before update) { //Create a new list for caseIds List<Id> caseIds = new List<Id>{}; //Loop through the Cases we're adding and build a list of Ids for(Case cas: Trigger.new) caseIds.add(cas.Id); List<Contact> addContacts = new List<Contact>(); // Loop through the Trigger.new array of Cases. for(Case cas:Trigger.new){ if (cas.SuppliedName != null) { addContacts.add(new Contact (LastName = cas.SuppliedName, Email = cas.SuppliedEmail, Phone = cas.SuppliedPhone, Email_ExtID__c = cas.SuppliedEmail)); } } upsert addContacts Email_ExtID__c; // loop thru contacts to retrieve contact ids Set<Id> ConIds = new Set<Id>(); for (Contact c: addContacts) { ConIds.add(c.Id); } List<Case> cases = new List<Case>{}; for (Case c : Trigger.new) { //c.Contact = ConIds; //cases.add(c); } update cases; }

I'm not correctly assigning the contact ids.  How can I do this?