You need to sign in to do that
Don't have an account?
pallavi elgonda
trigger:I am trying to update a field on Account upon updating a filed of all its contacts. But I see the update is not happening in the UI but in logs I can see it.
trigger contactTrigger on Contact (after insert,after update) {
List<Id> ids = new List<Id>();
for(Contact con: trigger.new){
ids.add(con.AccountId);
}
List<Account> aList= [select id,name, Task__c, (select id,Task__c from contacts) from account where id IN: ids];
for(Account acc: aList){
for(Contact con: acc.contacts){
system.debug('task'+con.Task__C+acc.Task__C);
if(con.Task__C=='Submitted'){
acc.Task__C='Achieved';
} system.debug('task'+con.Task__C+acc.Task__C+acc.Name);
}
}
}
List<Id> ids = new List<Id>();
for(Contact con: trigger.new){
ids.add(con.AccountId);
}
List<Account> aList= [select id,name, Task__c, (select id,Task__c from contacts) from account where id IN: ids];
for(Account acc: aList){
for(Contact con: acc.contacts){
system.debug('task'+con.Task__C+acc.Task__C);
if(con.Task__C=='Submitted'){
acc.Task__C='Achieved';
} system.debug('task'+con.Task__C+acc.Task__C+acc.Name);
}
}
}
Try the below way:
Thanks,
Maharajan.C
All Answers
Greetings!
Seems like the DML operation is missing after saving the values on the fields in the trigger.We need to use the Update statement to commit the changes.
update contacts;
Reference:https://salesforce.stackexchange.com/questions/23338/trigger-to-update-parent-object-value-with-child-value
Kindly let me know if it helps you and close your query by marking it as best answer so that it can help others in the future.
Warm Regards,
Shirisha Pathuri
Thank you.
Adding DML works for a single contact. When I have multiple contacts under one Account ,my code should check for all the contacts fields. If any of the contact under one account is not 'submitted' then the account field shouldn't update. Can you please help me to achieve this. I am new to coding environment. Thank You.
List<Id> ids = new List<Id>();
for(Contact con: trigger.new){
ids.add(con.AccountId);
}
List<Account> aList= [select id,name, Task__c, (select id,Task__c from contacts) from account where id IN: ids];
integer i=0;
for(Account acc: aList){
for(Contact con: acc.contacts){
system.debug('task'+con.Task__C+acc.Task__C);
if(con.Task__C=='Submitted'){
i=i+1;
} else{}
}
if(i==acc.contacts.size()){
acc.Task__C='Achieved';
}
} update aList;
Try the below way:
Thanks,
Maharajan.C