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
TracMikeLTracMikeL 

Most Efficient Trigger Code

I have a simple custom object with Contact and Account lookup.

 

When the contact is populated and the account is not, what is the most efficient trigger code to populate the account lookup from the contact?

 

Thanks!

Best Answer chosen by Admin (Salesforce Developers) 
SargeSarge

Hi,

 

    If a user doesnt populate account lookup and populates contact lookup, and hits save this is what trigger nneds to do

 

 

trigger PopulateAccount on Custom_Object__c (before insert, before update){
    list<Id> contactIds = new List<Id>();
    for(Custom_Object__c c: trigger.new){
       if(c.contact__c != null) 
contactIds.add(c.contact__c); } Map<Id,Contact> contactMap = new Map<Id, Contact>(); contactMap.putAll([Select Id, AccountId, Name from contact where id IN :contactIds]); for(Custom_Object__c c: trigger.new){ if(c.account__c == null && c.contact__c != null){ c.account__c = contactMap.get(c.Contact__c).AccountId; } } }

 

 

Here no need of any dml because we are just populatng account__c field (account lookup field in Custom_Object__c) and system will perform dml after this trigger execution.

 

 

 

All Answers

SargeSarge

Hi,

 

    If a user doesnt populate account lookup and populates contact lookup, and hits save this is what trigger nneds to do

 

 

trigger PopulateAccount on Custom_Object__c (before insert, before update){
    list<Id> contactIds = new List<Id>();
    for(Custom_Object__c c: trigger.new){
       if(c.contact__c != null) 
contactIds.add(c.contact__c); } Map<Id,Contact> contactMap = new Map<Id, Contact>(); contactMap.putAll([Select Id, AccountId, Name from contact where id IN :contactIds]); for(Custom_Object__c c: trigger.new){ if(c.account__c == null && c.contact__c != null){ c.account__c = contactMap.get(c.Contact__c).AccountId; } } }

 

 

Here no need of any dml because we are just populatng account__c field (account lookup field in Custom_Object__c) and system will perform dml after this trigger execution.

 

 

 

This was selected as the best answer
TracMikeLTracMikeL

perfect!