I want to update the account address if I update the associated contacts address. for that I have written a trigger but it didn't work.
both of the address fields are custom.
Trigger:
trigger UAddress on Contact (After insert, After Update) { list<Account> alist=new list<Account>(); if(Trigger.isInsert && Trigger.isUpdate){ For(Contact C: Trigger.new){ if(C.AccountId != Null && C.Address__c != Null){ Account A=new Account(); A.Id=C.AccountId; A.Address__c=C.Address__c; alist.add(A); } } if(alist.size() > 0){ Update alist; } } }
Hi Harshal,
Very important to note: you don't need code to achieve this. You can build a process that does this in minutes. But since this question comes up so often, I can assume you're doing this for some kind of exam/interview/training. So here are a few thoughts:
1. The main issue with your trigger is:
if(Trigger.isInsert && Trigger.isUpdate){
A trigger cannot be both Insert AND Update at the same time. Change that check to || and it should work, but with the following caveats:
2. As it stands, this trigger will run for any contact that's saved in the system - even if their address did not change. This will lead to longer save operations on contacts, and possibly result in governor limit failures in the future. You want to make sure the address changed by comparing the contact's address in Trigger.new to their equivalent in Trigger.old. You can use either Trigger.oldMap to get the old contact by ID, or if you want to be efficient, just get the contact from Trigger.old in the same index as Trigger.new.
3. This code will fail if you update two contacts belonging to the same account in the same transaction. Make sure that you only insert an account to the alist if it is not already there. You can do that by keeping a Set<Id> of the account IDs you processed. This also leads to a logical decision: what should happen if an account has 2 contacts with different addresses?
On a side note, are you sure that you understood the question correctly and you're meant to update the account? Normally, it's the account that changes and you're supposed to update the contacts.