+ Start a Discussion
SFDC Apex DevSFDC Apex Dev 

Please help me to bulkify the below trigger

trigger LinkEnCusToAccP on Acc_P__c (before insert, before update) {
    // Data load bypass    
    if(IsUtil.adminByPass()) return;
    
    Private Integer iCount = 0;

    for (Acc_P__c a : Trigger.new) {
        if(Trigger.isUpdate) {
            if(a.Account__c != Trigger.old[iCount].Account__c) {
                a.Ent_Cus__c = [select Ent_Cus__c from Account where Id = :a.Account__c limit 1].Ent_Cus__c;
            }
            iCount++;
        } else {
            if(a.Account__c != null) {
                a.Ent_Cus__c = [select Ent_Cus__c from Account where Id = :a.Account__c limit 1].Ent_Cus__c;
            }
        }
    }
}
Abdul KhatriAbdul Khatri
try this
 
trigger LinkEnCusToAccP on Acc_P__c (before insert, before update) {
    // Data load bypass    
    if(IsUtil.adminByPass()) return;

	List<Id> idAccountList = new List<Id>();    
    for (Acc_P__c a : Trigger.new) 
    {
		if(Trigger.IsInsert || (Trigger.IsUpdate && a.Account__c != Trigger.old(a.Id).Account__c))
            idAccountList.add(a.Account__c);
    }
    
    if(idAccountList.isEmpty()) return;
    
    Map<Id, Account> accountMap = new Map<Id, Account>([SELECT Ent_Cus__c FROM Account WHERE Id = :idAccountList]);
    
    for (Acc_P__c a : Trigger.new) {
        
        if(!accountMap.containsKey(a.Account__c)) continue;
               
        a.Ent_Cus__c = accountMap.get(a.Account__c).Ent_Cus__c;
    }
    
}