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
smitha george 5smitha george 5 

Trigger Logic sequence


I have account object when i enter A in Acc filed  i need to display A in contact field and when enters B then need to display like A,B
So what is the logic in trigger code?
Thanks in Advance.
Best Answer chosen by smitha george 5

I am assuming there is already a method that copies field data from Account to contacts on the insertion of account.

The logic is to append the new data from account to the existing data in the contact's field.
We need to read changes on account and update the child contacts accordingly, so the trigger should be written on the Account object on the update event. Please check the sample code below. Feel free to comment or correct.
Set<Id> accIdSet = new Set<Id>();
for(Account a : trigger.New){
if(a.FieldName__c!= Trigger.oldMap.get(a.Id).FieldName__c){
//Check if the value is changed, so as to append only if there is a change in the field
//this way you minimize the unwanted firing of the trigger

List<Account> AccountsAndContacts = [select id, FieldName__c, [select id, FieldName__c  from Contact]  from Account where id in: accIdSet];

List<Contact> tobeUpdatedContacts = new List<Contact>();

//the for loop goes this way
for(Account a : AccountsAndContacts){
 for(Contact c : a.contacts){
  //since contact is child to account, this is how you access child records from parent
  c.FieldName__c = a.FieldName__c +','+ c.FieldName__c;
 update tobeUpdatedContacts;