function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Carrie FarnsworthCarrie Farnsworth 

Trigger to update a field on child of a child

Hi All,

I'm trying to create a trigger (or use workflow rules) to update fields on the child record of a child record and I'm not sure how to do it (if it's even possible). 

The parent object is called Project__c.  Project__c is the parent to multiple Phase__c records which are parent to multiple Task__c records. When the Project_Status__c field on Project__c is set to cancelled, all associated Task__c records (under the associated Phase__c records) should be have the checkbox field IsCompleted__c set to TRUE and N_A__c checkbox set to TRUE.  Does anyone know how I can do this?
Best Answer chosen by Carrie Farnsworth
Amritesh SahuAmritesh Sahu
Hi Carrie,

Use following code
trigger <name> on Project__c (after update) {

List<Project__c> projects_to_process = new List<Project__c>();

for(Project__c project : Trigger.New)
{
    if(project.Project_Status__c == 'Cancelled')
          projects_to_process.add(project);
}

List<Task__c> tasklist = new List<Task__c>(
[select id,name,IsCompleted__c,N_A__c from Task__c where Phase__c in (select id from Phase__c where Project__c in :projects_to_process)]
);
for(Task__c task : tasklist)
{
    task.IsCompleted__c = true;
    task.N_A__c = true;
}
update tasklist;

}

Thanks,
Amritesh

All Answers

mjohnson-TICmjohnson-TIC

You could try something like this on an after update trigger.

if(trigger.new[0].Project_Status__c == 'cancelled' && trigger.new[0].Project_Status__c <> trigger.old[0].Project_Status__c){
try{
list<Task__c> tl = new list<Task__c>();
for(Task__c t: [Select IsCompleted__c from Task__c where Phase__r.Project__c =: trigger.new[0].Id)]{
t.IsCompleted__c = true;
tl.add(t);
}
if(tl != null){
update tl;
}
}catch(exception e){
// no child of child records found
}
}

Amritesh SahuAmritesh Sahu
Hi Carrie,

Use following code
trigger <name> on Project__c (after update) {

List<Project__c> projects_to_process = new List<Project__c>();

for(Project__c project : Trigger.New)
{
    if(project.Project_Status__c == 'Cancelled')
          projects_to_process.add(project);
}

List<Task__c> tasklist = new List<Task__c>(
[select id,name,IsCompleted__c,N_A__c from Task__c where Phase__c in (select id from Phase__c where Project__c in :projects_to_process)]
);
for(Task__c task : tasklist)
{
    task.IsCompleted__c = true;
    task.N_A__c = true;
}
update tasklist;

}

Thanks,
Amritesh
This was selected as the best answer
Carrie FarnsworthCarrie Farnsworth
Thanks Amritesh -- this worked perfect!