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
Irvine DelacroixIrvine Delacroix 

Help with Bulkification

Hi Experts,

I'm still confused with how to bulkify the Codes so I don't reach the Governor Limit. I've created some Triggers in our sandbox but it seems that this is not bulkified even though it's working. Can anyone give me Idea on the best practice and how to bulkify the code below.. Thanks :)

/*Mainly, here's the story of my code.. There are two related lists under Account, the ObjectA and ObjectB. I want to have a value (Hourly) from ObjectB to Test__c from ObjectA when ObjectA is Created or Updated */

trigger TestField on ObjectA (before insert, before update) {
    
    Set<Id> AccIDs = new Set<Id>(); //store Account IDs where ObjectA is associated
    String Type;  //Get the Type of the ObjectA (Picklist)
    
    For(ObjectA__c ObjA:Trigger.new){
        AccIDs.add(ObjA.Account__c);
        Type = ObjA.Type__c;
    }
    
    //Create a list of ObjectB where Account ID is equal to the Account ID from ObjectA and the type is equal to the Type of ObjectA.
    List<ObjectB__c> ObjB = [SELECT id, Hourly__c, Type__c  
                                    FROM ObjectB__c
                                    WHERE Account__c IN: AccIDs AND Job_Type__c = : Type];

     //Update the field Test__c from Object A with the Hourly value from the Related List ObjectB from Account.                       
    For(ObjectA__c Obj:Trigger.new) {
            Obj.Test__c = RateCards[0].Hourly__c;
    }

}



Thanks in advance :)
SaranSaran
Hi irvine,


Just modify the code according to your object name and fields

trigger test on objA (before insert , before update)
{
    map<id, map<string , integer>> map = new map<id, map<string , integer>>();
    
    for(objA oA : trigger)
    {
        accSet(oA.accountId);
    }
    
    for(objB oB : [select id, accountId, hourly__c, type from objB where accountId in: accSet])
    {
        if(map.contains(oB.accountId))
        {
            map.get(oB.accountId).put(oB.type , oB.hourly__c);
        }
        else
        {
            map.put(oB.accountId , new map<string , objB>{oB.type => oB.hourly__c});
        }
    }
    
    for(objA oA : trigger.new)
    {
        if(map.contains(oA.accountId) && map.get(oA.accountId).contains(oA.type))
        {
            oA.hour__c = map.get(oA.accountId).get(oA.type).hourly__c;
        }
    }
}


Like this if the solution has solved.

Thanks,
Saraz