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
niki s 7niki s 7 

Before insert trigger code optimization

Hello I am writing a trigger on contact object where if I select account lookup field than account s country also get populated in contact object.
code is working fine just need to optimised it .

 
public class UpdateContactRecordsFromAccount {

   
    public void beforeInsert(List<Contact > neWValues)
    {
       Set<ID> id_po = new Set<ID>();
      for(Contact po : newValues){
            id_po.add(po.AccountId);
        }
       
     List<Account> AccountList = [select id , Country__c  from Account where Id in : id_po];
     for(Contact con : neWValues){  
          for(Account  acc : AccountList)
          {
           con.Country__c = acc.Country__c;
            
          }
       }
    }
}

Please help 
Lukesh KarmoreLukesh Karmore
Hello  niki s 7,
 I think the above code is not  correct trigger syntex.  check link...
https://www.sfdcpoint.com/salesforce/apex-trigger-in-salesforce/
mark if helps.
Thank You
niki s 7niki s 7
public class UpdateContactRecrdsFromAcc {
 public void beforeInsert(List<Contact > neWValues) {
       Set<ID> id_po = new Set<ID>();
      for(Contact po : newValues){
            id_po.add(po.AccountId);
 for(Account acc : select id , Country__c from Account where Id in : id_po])
          {
          con.Country__c = acc.Country__c;
          }
       }
    }
}

Can I optimized it more??
Abhishek BansalAbhishek Bansal
Hi,

Please use the below code:
public class UpdateContactRecrdsFromAcc {
	public void beforeInsert(List<Contact > neWValues) {
		Set<ID> id_po = new Set<ID>();
		for(Contact po : newValues){
			id_po.add(po.AccountId);
		}
		Map<Id, Account> mapOfAccounts = new Map<Id, Account>([select id , Country__c from Account where Id in : id_po]);
		for(Contact po : newValues){
			con.Country__c = mapOfAccounts.get(po.AccountId).Country__c;
		}
	}
}

Let me know if there is an issue.

Thanks,
Abhishek Bansal.
abhibansal2790@gmail.com​​​​​​​
niki s 7niki s 7
Thanks abhi