How to trigger for this scenario "if account email is changed change all associated contact email id which initially had same email id as that of the account"
Write a trigger on Account object with after update event, on after update get the contact associate with the account and update the contact records with account email.
Hi chidambarakumari, Try this and let me know. Account field - Email__c Contact Field - Email public void updateContactEmail(List<Account> accountnew,Map<ID,Account> oldAccount){ Map<String,Account> accountRec = new Map<String,Account>(); Map<ID,Account> accountEmailRec = new Map<ID,Account>(); for(Account record : oldAccount.values()){ accountRec.put(record.ID,oldAccount.values()); } List<Contact> contactEmailRec = new List<Contact>(); for(Account emailAcc : accountnew){ accountEmailRec.put(emailAcc.ID,emailAcc); }
for(Contact conRec : [SELECT Id,Email,AccountId from contact where AccountId IN :oldAccount.keySet()]){ for(Id accRec : oldAccount.keyset()){ if(conRec.AccountId == oldAccount.get(accRec).Id){ if(conRec.Email == accountRec.get(conRec.AccountId).Email__c) { conRec.Email = accountEmailRec.get(conRec.AccountId).Email__c;
Set<id> accoun = new Set<id>();
for(Account acc : Trigger.old)
{
accoun.add(acc.id);
}
List<contact> con = [select id,email from Contact where accountid IN :accoun];
for(Account a : Trigger.New)
{
if(trigger.oldMap.get(a.id).email__c != trigger.newMap.get(a.id).email__c)
{
for(Contact c : con)
{
c.email = a.email__c;
}
}
}
update con;
}
All Answers
Write a trigger on Account object with after update event, on after update get the contact associate with the account and update the contact records with account email.
Try this and let me know.
Account field - Email__c
Contact Field - Email
public void updateContactEmail(List<Account> accountnew,Map<ID,Account> oldAccount){
Map<String,Account> accountRec = new Map<String,Account>();
Map<ID,Account> accountEmailRec = new Map<ID,Account>();
for(Account record : oldAccount.values()){
accountRec.put(record.ID,oldAccount.values());
}
List<Contact> contactEmailRec = new List<Contact>();
for(Account emailAcc : accountnew){
accountEmailRec.put(emailAcc.ID,emailAcc);
}
for(Contact conRec : [SELECT Id,Email,AccountId from contact where AccountId IN :oldAccount.keySet()]){
for(Id accRec : oldAccount.keyset()){
if(conRec.AccountId == oldAccount.get(accRec).Id){
if(conRec.Email == accountRec.get(conRec.AccountId).Email__c) {
conRec.Email = accountEmailRec.get(conRec.AccountId).Email__c;
}
}
}
contactEmailRec.add(conRec);
}
update(contactEmailRec);
}
Set<id> accoun = new Set<id>();
for(Account acc : Trigger.old)
{
accoun.add(acc.id);
}
List<contact> con = [select id,email from Contact where accountid IN :accoun];
for(Account a : Trigger.New)
{
if(trigger.oldMap.get(a.id).email__c != trigger.newMap.get(a.id).email__c)
{
for(Contact c : con)
{
c.email = a.email__c;
}
}
}
update con;
}