0

The requirement is : I need the Description field on each Opportunity to match that on the parent Account. To achieve this we can write a working trigger like this

 trigger AccountTrigger on Account (after insert,after update) {
 List<Opportunity> opps = [
        SELECT Id, Description, Account.Description
        FROM Opportunity
        WHERE AccountId IN :Trigger.new
    ];
    Map<Id, Opportunity> updateMap = new Map<Id, Opportunity>();

    for (Opportunity o : opps) {
                o.Description = o.Account.Description;
                updateMap.put(o.Id, o); 
    }

    update updateMap.values();
}

To experiment i tried updating after update and after insert to before update and before insert

 trigger AccountTrigger on Account (before insert,before update) {
     List<Opportunity> opps = [
            SELECT Id, Description, Account.Description
            FROM Opportunity
            WHERE AccountId IN :Trigger.new
        ];
        Map<Id, Opportunity> updateMap = new Map<Id, Opportunity>();
    
        for (Opportunity o : opps) {
                    o.Description = o.Account.Description;
                    updateMap.put(o.Id, o); 
        }
    
        update updateMap.values();
    }

but the trigger didn't seem to do its job. Can somebody let me know the reason why after trigger worked and not before trigger?

1

The before triggers don't work, because the records haven't been saved to the database yet. Therefore, your code queries the old account description, before it was updated. You can fix this by using the records in Trigger.newMap:

 List<Opportunity> opps = [
        SELECT AccountId
        FROM Opportunity
        WHERE AccountId IN :Trigger.new
    ];
 for(Opportunity record: opps) {
    record.Description = Trigger.newMap.get(record.AccountId).Description;  
 }
 update opps;

Note that there's no point in triggering on insert, as child records cannot exist before their parents do. You only need a before update or after update trigger.

Also, it is a Best Practice to update related (parent/child) records only in an after trigger, because other triggers may change the description and save the wrong data to the opportunity.

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.