Skip to content

Salesforce Apex Trigger: Changing the field value of Child Objects based on a change to the Parent Object

 

Salesforce Admin Tips
Cross-Object field updates can be achieved quite easily using Work Flow Rules where a change to a detail record, updates a field on a related parent object. The reverse, however, is not so simple. Work Flow rules fail when you want to trigger a field update on child objects based on a change to the related parent object. Lets say for example, you want to flag all contacts when a specific field of the related account changes. Of course, you could create a lookup formula field on the child object which simply displays the value of a field on the parent object. The issue with that solution is that a lookup formula field simply mirrors the value of the field it reads from, a change in such a field is not a ‘true change’ recognised by Salesforce, which makes it impossible to trigger further actions off the back of the contact field changing. This is where Salesforce’s Apex triggers come into play. In this blog, I will provide an example case where I used an Apex trigger to solve a problem that simply could not be solved using Salesforce Workflow Rules.

The Example Case:

We wanted to send an email to all contacts, from accounts that purchased a subscription. Originally I thought I could write a Workflow Rule that sent an email based off of the Account Type field changing from Prospect to Customer on the Contact Record. The problem here was the Account Type was simply a formula field that displayed the Account Value on a Contact record. Therefore when the field changed from Prospect to Customer the Workflow Rule did not kick in. To get around this problem I created a custom checkbox field, “Customer” on the Contact Page Layout and another custom checkbox field “Subscribed” on the Parent Account. I then wrote an Apex Trigger which checked/ticked every Contact’s ‘Customer’ checkbox field whenever their Parent Account’s ‘Subscribed’ checkbox field was checked/ticked. On achieving this it was easy to set up a Salesforce Workflow rule that sent an email to contacts who have the Customer Checkbox ticked.

Heres the Apex Trigger Code I used:

1  trigger SubscriptionEmail on Account (after update) { 2 3 4                  for(Account acc: Trigger.new){ 5                          Account oldAcc = Trigger.oldMap.get(acc.Id); 6                          if(oldAcc.Subscribed__c != acc.Subscribed__c && acc.Subscribed__c == true) 7                                  { 8                                          List<Contact> children = [ SELECT Id, AccountId, Customer__c from 9                                          Contact where AccountId = :acc.Id]; 10                                        List<Contact> newids = new List<Contact>(); 11 12                                        for(Contact con: children){ 13                                                if(con.Customer__c != acc.Subscribed__c){ 14                                                        con.Customer__c = acc.Subscribed__c; 15                                                newids.add(con); 16                                                } 17                                        } 18                                        if (newids.isEmpty()== false){ 19                                                update newids; 20                                       } 21                                } 22                 } 23  }

How to deploy the Salesforce Apex Trigger

First and foremost you will need to be in a a sandbox Performance, Unlimited, or Enterprise Edition organization, or an account in a Developer organization as Salesforce do not allow you to write Apex code in a live environment. Next, complete the steps below: . Log into your sandbox environment. . Click on Setup > Customize. . Click on the parent object you are going to write a trigger on. . Click on “Triggers” and then “New” An editer will open which will contain code very similar to the code below. You will use this editor to write your own Apex trigger.         trigger <name> on Account (<events>) {           }

Writing your own Apex trigger:

* Sections of the code highlighted in green may need to be modified.
I will now go through each part of the code I used and highlight the sections you may need to modify in your code.         trigger SubscriptionEmail on Account (after update) { A Salesforce trigger will always start with the keyword “trigger”. “SubscriptionEmail” is the name of the trigger, you can change this to what best describes your trigger. “on Account” states what type of record the trigger is on. This will always be the parent object. “(after update)” simply means, this trigger will be reviewed after you update your parent object, “Account” in my case. (Most of this will be done for you if you followed the steps provided above)        for(Account acc: Trigger.new){ This simply starts the process. In basic English, it means for the account (again, change this to your parent object) which has been updated, perform the actions in the curly brackets. “acc” is a friendly name I have given to the account updated, you can change this to what you want.         Account oldAcc = Trigger.oldMap.get(acc.Id);           if(oldAcc.Subscribed__c != acc.Subscribed__c && acc.Subscribed__c == true) This part of the code ensures that the Account field “Subscribed” has been changed from false to true, “acc.Subscribed__c == true” is the condition in my case, you may need to change this to suit your needs. “Subscribed__c” is the API name of the account custom field which I created, change this to the API name of your custom field. “oldAcc” is a friendly name I have given to the state of the account, which has been updated, before the update. Once again, you can change this to what you want.    List<Contact> children = [ SELECT Id, AccountId, Customer__c from           Contact where AccountId = :acc.Id]; This simply returns a list of child objects of the related parent object that has been updated. In my case, this is a list of contacts, change “Contact” to your child object (remember to to also change the field “AccountId” to your child object’s field which holds the Id of the parent object). Remember the aim of this trigger to change the contact’s custom field “Customer” to true if the account’s custom field “Subscribed” has been set to true, so in your list you will need to return said custom field by including its API name, “Customer__c” in my case. “children” is a friendly name I have given my list, you can change this to what you want.    List<Contact> newids = new List<Contact>(); This simply creates a second list of the same child object, I plan on using this to update my child objects. Once again, “newids” is a friendly name I have given my second list, feel free to change this.    for(Contact con: children){                    if(con.Customer__c != acc.Subscribed__c){                            con.Customer__c = acc.Subscribed__c;                            newids.add(con);                    }            } The code above, sets the value of the contact’s custom field “Customer” to the same value as the account’s custom field “Subscribed”, which we know has been set to true. It then adds the contact to our second list “newids”. This is done for every contact of the related account.    if (newids.isEmpty()== false){                  update newids;          } This is the final piece of the code which simply updates all contacts which have been added to our list “newids”. Once you are happy with your Apex code, click on “Save”. Congratulations, you have just written an Apex trigger which updates all child objects based on a change made to the related parent object. Once you have ensured your trigger works in your sandbox environment, the next step is to test and deploy to live production. The links below will assist you in both writing a unit test and deploying your Apex trigger to your live environment. Good luck! https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_qs_HelloWorld.htm https://developer.salesforce.com/forums/ForumsMain?id=906F00000008wqAIAQ

Soroosh Avazkhani

Junior Developer at Ebsta. Obsessed with finding and sharing all the best Salesforce Admin hacks to help you achieve Salesforce greatness!

Related Posts

Give your Sales Reps access to the best data

Long gone are the days where you had to rely on your Reps to add emails or data into Salesforce. Ebsta does it automatically. Reps now have access to 100% data accuracy without having to do a thing.
Find out more