4

I currently have this trigger which updates the Parent of the record being saved with field values from the GRANDparent of the record being saved :

trigger updateParentwithGrandparent on Grandchild__c (after insert) {

    // Get a list of all Parent Ids
    Set<Id> parentIds = new Set<Id>();
    for (Grandchild__c gc : trigger.new) {
        parentIds.add(gc.MyParent__c);
    }

    // Get a map of all Parents with Grandparent field information
    Map<Id, Parent__c> parentsById = new Map<Id, Parent__c>();
    parentsById.putAll([SELECT Id, MyParent__r.MyField__c FROM Parent__c WHERE Id IN :parentIds]);

    // Loop through each parent and update Parent.MyField__c from Grandparent.MyField__c
    List<Parent__c> parentsToUpdate = new List<Parent__c>();
    for (Id parentId : parentsById.keySet()) {
        Parent__c parent = new Parent__c();
            parent.Id = parentId;
            parent.MyField__c = parentsById.get(parentId).MyParent__r.MyField__c;
        parentsToUpdate.add(parent);
    }

    // Update Parents (bulkified)
    update parentsToUpdate;

}

So it looks up 2 levels of hierarchy and pulls those values down one level to its parent.

But now I am attempting to adapt this code so it would instead update the current record with values from its Parent.

In other words, there is no need for a Grandparent. It will only be looking up one level of hierarchy and pulling those field values into the current record which is being saved.

Can anybody help with this ? I'm confused on how to do this.

Thank you very much for your time and effort.

7
    trigger updatechildwithparent on child__c (before insert) {

   // Get a list of all Parent Ids
   Set<Id> parentIds = new Set<Id>();
    for (child__c chld : trigger.new) {
      parentIds.add(chld.MyParent__c);
   }

   // Get a map of all Parents with field information
Map<Id, Parent__c> parentsById = new Map<Id, Parent__c>();
parentsById.putAll([SELECT Id, MyParentfield1__c,MyParentfield2__c FROM Parent__c WHERE Id IN :parentIds]);

 for(child__c chld:trigger.new()){ 
      chld.chldfield1__c=parentsById.get(chld.MyParent__c).MyParentfield1__c;
      chld.chldfield2__c=parentsById.get(chld.MyParent__c).MyParentfield2__c;
   }

}

If fields are of currency type be sure to check null pointers .

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.