2

I have a custom object called Location__c that has a date field called Active_Date__c. Location__c has a child object called Cans__c. Cans__c has a date field Start_Date__c. I would like to write a trigger that populates the child dates with the master date. I am very new to this, so be gentle. Here is what I have so far:

trigger addActiveDateToChildStartDate on Location__c(after insert, after update){

    Can__c[] canList = new can__c[0];
    Map <Id,Can__c> servicesMap = new Map<id,Can__c>();

    locations.putAll([SELECT Id,Active_Date__c,(SELECT Id, Start_Date__c FROM Cans__r)FROM Location__c WHERE Id In :locations.keySet()]);
    for (Location__c Loc: locations){
        List<Can__c> services = Loc.getSObjects('Can__c');
        servicesMap.put(Loc.Id, Can__c);
    }   
}

Any help would be appriciated, Thanks!

1 Answer 1

2

Try something like this. This is making a few assumptions on your field names but this should give you the general idea.

All you need to do is query the child records that are related to the Location objects in the trigger context. From there, you can just grab the Active Date of the parent Location object by using the trigger.newMap context variable.

trigger addActiveDateToChildStartDate on Location__c(after insert, after update){

    list<Can__c> childCans = [Select Id, Start_Date__c, Locations__c From Can__c Where Locations__c IN : Trigger.new];

    for(Can__c can : childCans){
         can.Start_Date__c = trigger.newMap.get(can.Locations__c).Active_Date__c;
    }
    update childCans;
}
7
  • Thanks, It saved without errors once I changed Location__c to Locations__c in SOQL Query and assignment. Commented Feb 4, 2015 at 16:43
  • Testing it by entering an active date in the sandbox gives me: Error: Invalid Data. Review all error messages below to correct your data. Apex trigger addActiveDateToChildStartDate caused an unexpected exception, contact your administrator: addActiveDateToChildStartDate: execution of AfterUpdate caused by: System.SObjectException: SObject row was retrieved via SOQL without querying the requested field: Can__c.Locations__c: Trigger.addActiveDateToChildStartDate: line 5, column 1 Commented Feb 4, 2015 at 16:43
  • Updated the code. Try that Commented Feb 4, 2015 at 16:53
  • See if I understand: trigger addActiveDateToChildStartDate on Location__c(after insert, after update) : After because the active date needs to be saved so that it is available to be assigned to the child records? Commented Feb 4, 2015 at 18:12
  • list<Can__c> childCans = [Select Id, Start_Date__c, Locations__c From Can__c Where Locations__c IN : Trigger.new]; list holds can id's, start date, and location id related to can that are contained within trigger new? Commented Feb 4, 2015 at 18:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .