Cross object reference field in salesforce using trigger


Cross object reference means to refer the value from a field from the parent object to child object, this can be easily be done using a formula field but sometime we may face some scenario where we have to lookup the value from the parent object to child object using the trigger, there could be any scenario as today i have face an issue where i was not allow to create more cross reference fields because the object has reach its limit, you can read about that more here .

Trigger is quite simple but we have to keep in mind the best practices of salesforce , so we will make a trigger which will run over the multiple records at once, if we say that trigger has to work upon the multiple records at one then we have to use the list and maps for that or in short we have to use the collections for that.


We will take a scenario, we will assume that we have the child object with name ‘Child‘ and have a parent object with name ‘Parent‘, now now we further assume that we have a field ABC on child object on which we have to populate the value from the parent object field which, let say XYZ, so the trigger would be like

trigger childTrigger on child (after Update) {
            //this will send all the records which is getting updated on child object to childtriggerhelper class


In the above trigger it will send the records which currently in process to a helper class, getting all the information from the trigger to class is best practice and recommend by salesforce as well. Now see the below code for the helper class

public Static void populatechildObjectField(list<child> childID) {

    list<child> childList=new list<child>();
    map<ID,child> childMap=new map<ID,child>();
    // parentFieldName.Name, this will give you the value of the parent field, see the below soql quesry
    childList=[Select  id,parentFieldName.XYZFrom child c where id=:childID];
    //Now we have all the parent object field values in a list and now we need to extract that and assign it to out current processing child object field, so to do that we have to use a map which i have declare above.

    for(child cc: childList){	
   	   update childMap.values();

parentFieldName, must be a lookup field to parent object on your child object, as you’re fetching the value from parent object, so you have to use the API name of the lookup field and concatenate it with DOT and then finally write the name of the field from parent object whose value you want to cross reference in the child object. Let me know if you didn’t get anything or else if you have any questions.

Related Articles :

Speak Your Mind



This site uses Akismet to reduce spam. Learn how your comment data is processed.