You need to sign in to do that
Don't have an account?
Please help me writing trigger for this scenerio
I want to write a trigger:
I've one 'Account' object and 'Contact' is its child object. In 'Account Object' there is a custom field Name 'Contact_Name__c'.
If i inserts any record in 'Contact' object than its 'First Name' field value copies into the 'Contact_Name__c' field.
I wants that all 'Contact' Object records 'First Name' copies into 'Contact_Name__c' field those are in relationship with that 'Account' Object.
For Example:
If Account Name-'Acc' and in Child 'Contact' have 3 records.
and First Name of these records are- 'Nitin', 'Rahul', 'Ashwani'
Now i want these field values in Contact_Name__c field
Contact Name: Nitin, Rahul, Ashwani
So how i can do this. Please help me to write trigger for it.
try this
trigger UpdateContactName on Contact(after insert){
List<Account> accListToBeUpdated = new List<Account>();
Map<ID,Account> accMap = new Map<ID,Account>([SELECT id,name,Contact_Name__c FROM Account WHERE id in :Trigger.new.AccountId]);
for(Contact con : Trigger.new){
Account acc = new Account();
if(con.AccountId != NULL){
acc = accMap.get(con.AccountId);
if(acc.Contact_Name__c == NULL){
acc.Contact_Name__c = con.name;
}
else{
acc.Contact_Name__c += ',' + con.name;
}
}
accListToBeUpdated.add(acc);
}
if(accListToBeUpdated.size() > 0){
update accListToBeUpdated;
}
}
}
If this post is helpful please throw Kudos.If this post solves your problem kindly mark it as solution.
Thanks
All Answers
try this
trigger UpdateContactName on Contact(after insert){
List<Account> accListToBeUpdated = new List<Account>();
Map<ID,Account> accMap = new Map<ID,Account>([SELECT id,name,Contact_Name__c FROM Account WHERE id in :Trigger.new.AccountId]);
for(Contact con : Trigger.new){
Account acc = new Account();
if(con.AccountId != NULL){
acc = accMap.get(con.AccountId);
if(acc.Contact_Name__c == NULL){
acc.Contact_Name__c = con.name;
}
else{
acc.Contact_Name__c += ',' + con.name;
}
}
accListToBeUpdated.add(acc);
}
if(accListToBeUpdated.size() > 0){
update accListToBeUpdated;
}
}
}
If this post is helpful please throw Kudos.If this post solves your problem kindly mark it as solution.
Thanks
Try below trigger, It will support insert, update and delete operation. Also if you change account then it will update both accounts.
I have tested this trigger and it works fine for me.