+ Start a Discussion
raysfdc1988raysfdc1988 

bulkify the trigger



trigger pudatename on BuyAirtime__c (before insert, before update) {
for(BuyAirtime__c  ba: trigger.new)
{
user us =[select id,name from user where id=:ba.Mentor__c];

ba.Name = us.name +' '+ ((ba.Buy_Airtime_Date__c).day()+'/'+(ba.Buy_Airtime_Date__c).month()+'/'+(ba.Buy_Airtime_Date__c).year());
}
}

As trigger is working fine but to bulkify this trigger i want to write the soql query  out of for loop..pl help me
Vamsi KrishnaVamsi Krishna
Hi,

you can try this..

first get all the user ids from the lookup field
then query all the user fields based on the ids
finally update the name field

trigger pudatename on BuyAirtime__c (before insert, before update) {

Set<Id> mentorIds = new Set<Id>();

for(BuyAirtime__c  ba: trigger.new)
{
  mentorIds.add(ba.Mentor__c);
}

Map<Id,user> userMap = new Map<Id,User>([select id,name from user where id=:mentorIds]);

for(BuyAirtime__c  ba: trigger.new)
{
  User us = userMap.get(ba.Mentor__c);
  ba.Name = us.name +' '+ ((ba.Buy_Airtime_Date__c).day()+'/'+(ba.Buy_Airtime_Date__c).month()+'/'+(ba.Buy_Airtime_Date__c).year());
}

}

CheyneCheyne
Since the User record is related to the Buy_Airtime record, you should be able to just run a query for all of the records in trigger.new, but accessing the related user fields that you need.

List<BuyAirtime__c> buyAirtimes = [SELECT Id, Mentor__r.Name, Buy_Airtime_Date__c FROM Buy_Airtime__c WHERE Id IN trigger.newMap.keySet()];
for (Buy_Airtime__c ba : buyAirtimes) {
    ba.Name = ba.Mentor__r.Name +' '+ ((ba.Buy_Airtime_Date__c).day()+'/'+(ba.Buy_Airtime_Date__c).month()+'/'+(ba.Buy_Airtime_Date__c).year());
}


raysfdc1988raysfdc1988
thanks vamsi.. its working..

raysfdc1988raysfdc1988
thanks  cheyne..
Vamsi KrishnaVamsi Krishna
ray,
glad it helped you.. please mark it as solved. :-0