You need to sign in to do that
Don't have an account?
SeniorMove
Trigger to update fields on related object
This seems so simple but I can't get it to work.
I want to copy 2 fields from one object to another:
Move_To_State_Province__c on Move__c copied to Mailing_State__c on Client__c
Move_To_Country on Move__c copied to Mailing_Country__c on Client__c
I've cobbled together the code based on solutions here on the board. It saves fine, but nothing happens. What am I missing? Also, once it works, how would you write a test for it?
Thanks! I'm stumped!
trigger NewMailingStateAndCountry on Move__c (after insert, after update) { for(Move__c mov : Trigger.New){ List<Client__c> listClient = [Select Mailing_State__c, Mailing_Country__c from Client__c]; for(Client__c client : listClient){ client.Mailing_State__c = mov.Move_To_State_Province__c; client.Mailing_Country__c = mov.Move_To_Country__c; } update listClient; } }
you are missing a codeline (listClient.add(client);) in the for loop
please write the test method for bulk testing also in similar lines (by creating multiple Move__c records and Client__c records)
Thank you. I tried that, but now receive the following error:
Apex trigger NewMailingStateAndCountry caused an unexpected exception, contact your administrator: NewMailingStateAndCountry: execution of AfterUpdate caused by: System.FinalException: Cannot modify a collection while it is being iterated: Trigger.NewMailingStateAndCountry: line 4, column 9
keep this line of code out side of the for loop as below
for(Move__c mov : Trigger.New){
....
for(...){
....
}
....
}
update listClient;
Dont understand your logic. What will happen if Trigger.New has more than 1 value. All Client__c values fetched will be overwritten by last Move__C value from trigger. I think you are missing some where clause.
Also move update listClient; outside the outer for loop.