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
HelloSanHelloSan 

how to bulkify this trigger failing to take morethan 100 records

trigger OwnerAccountPopulateTrg on Opportunity (before insert,before update) {
for(opportunity opp:trigger.new)
{
Set<Id> accids = new Set<Id>();
if(opp.accountId != null){
accids.add(opp.accountid);
}
if(accids.size()>0)
{
Map<Id,Id> mpOwners = new Map<id,Id>();
for(Account acc : [Select id, ownerId from Account where id in:accids])
{
mpOwners.put(acc.id,acc.ownerId);
}
for(Opportunity opp1:trigger.new){
//Custom Owner Field
opp1.New_User__c = mpOwners.get(opp.accountId);
}
}
}
}
Bhanu MaheshBhanu Mahesh
Hi HelloSan,

Your trigger is not bulkified because your entire code is in for loop and so it is executing for every record single time.

Try below code
trigger OwnerAccountPopulateTrg on Opportunity (before insert,before update) {
	Set<Id> accids = new Set<Id>();
	Map<Id,Id> mpOwners = new Map<id,Id>();
	for(opportunity opp:trigger.new){
		if(Trigger.isInsert){
			if(opp.accountId != null){
				accids.add(opp.accountid);
			}
		}
		if(Trigger.isUpdate){
			if(opp.accountId != null && opp.accountId != trigger.OldMap.get(opp.Id).accountId){
				accids.add(opp.accountid);
			}
		}
	}
	if(accids.size()>0){
		for(Account acc : [Select id, ownerId from Account where id in:accids]){
			mpOwners.put(acc.id,acc.ownerId);
		}
		for(Opportunity opp1:trigger.new){
		//Custom Owner Field
			if(opp.accountId != null && mpOwners != null && mpOwners.get(opp.accountId) != null){
				opp1.New_User__c = mpOwners.get(opp.accountId);
			}
		}
	}
}

Refer the below links for trigger bulkifying triggers
https://developer.salesforce.com/page/Apex_Code_Best_Practices

Regards,
Bhanu Mahesh

Mark this as "SOLVED" if your issue is resolved
SF AdminSF Admin
Hi,
You just need to write your code outside the for loop.
 
trigger OwnerAccountPopulateTrg on Opportunity (before insert,before update) {
	Set<Id> accids = new Set<Id>();
	Map<Id,Id> mpOwners = new Map<id,Id>();
	for(opportunity opp:trigger.new){			
			if(opp.accountId != null){
				accids.add(opp.accountid);
			}
	}
	if(accids.size()>0){			
		for(Account acc : [Select id, ownerId from Account where id in:accids]){
			mpOwners.put(acc.id,acc.ownerId);
		}
	}
	for(Opportunity opp1:trigger.new){
		if(opp1.accountId != null && mpOwners.get(opp1.accountId) != null){
			//Custom Owner Field
			opp1.New_User__c = mpOwners.get(opp1.accountId);
		}
	}
}
Important :
If this is what you were looking for then please mark it as a "SOLUTION" or You can Click on the "Like" Button if this was beneficial for you.