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
Vinit Sharma94Vinit Sharma94 

Help on Trigger

Hi,

I have one scenario where Account has one custom field Email__c(Long Text) and this account has multiple Contacts. Each contact Email field. I want to write a Trigger on  Contact when there is new contact comes it's email field also populate in the Account's custom field which is Email__c and all the email of contacts are separated by ; when we delete this contact it's Email also gets deleted from Account's custom field which is Email__c.

Please find enclosed code:-
trigger emailupdate on Contact (after insert, after update, after delete) {
    if(trigger.IsAfter && trigger.isInsert)
    {    
        List<Account> li = new list<Account>();
        List<Id> ids = new List<Id>();
        //String allEmailOfContacts = '';
        for(Contact c : trigger.new){
            ids.add(c.AccountId);
        }
        Map< Id, Account> accountMap = new Map<Id, Account>([Select Id,Email__c from Account where Id In:ids]);
        for(Contact c: trigger.new)
        {
            Account a = accountMap.get(c.AccountId);
            if(a != null)
            {
                a.Email__c += c.Email+ ';';
                //allEmailOfContacts = allEmailOfContacts + c.Email + ';';        
                li.add(a);
            }
        }
        update li;
    }

}

Andrew GAndrew G
You could try something like:
trigger updateAccountEmail on Contact (after insert, after update, after delete) {

    if(trigger.IsAfter && trigger.isInsert)
    {    
        List<Account> accountList = new list<Account>();
//lets use a set , rather than list, as we want the Account once only
        Set <Id> accountIdsSet    = new Set<Id>();
//get a list of all account Ids for contacts being updated
        for(Contact c : trigger.new){
            accountIdsSet.add(c.AccountId);
        }
//create a Map of those Accounts
        Map< Id, Account> accountMap = new Map<Id, Account>([Select Id,Email__c from Account where Id In :accountIdsSet]);

//a map to hold the concatenated emails, keyed by Account id
	Map<Id,String> mapEmails = new Map<Id,String>();
//do a query of all contacts associated with Accounts where a contact has been updated
//so if one contact is updated, inserted or deleted(?) we get all the other contacts and re-write the full email list
	for(Contact c: [SELECT Id, AccountId, Email FROM Contact WHERE AccountId IN :accountIdsSet ORDER BY AccountId])
//note the ORDER by is not really necessary, but may make it easier to trouble shoot
	{
//if key exists, update the existing entry
		if(mapEmails.containsKey(AccountId) )
		{
			String emails = mapEmails.get(AccountId);
			emails += c.Email+ ';';
			mapEmails.put(AccountId,emails);
		}
		else
		{
//create a new Map entry with the initial email address
			mapEmails.put(AccountId, c.Email);
		}
	}
//now we have a map with key of Account ID and an associated String of all emails concatenated wiht a semi colon

//so loop the map of actual accounts and use the common key of Account Id to update the Account records
	for (Id aId : accountMap.getKey())
	{
		Account acc = accountMap.get(aId);
		acc.Email__c = mapEmails.get(aId);
//add to a list so we only do the DML once.
		accountList.add(acc);
	}
	update accountList;

}

the above code may also be suitable for onDelete, hopefully the logic makes sense.  
Note, the code has not been compiled, only written in a basic text editor.


regards
Andrew
Vinit Sharma94Vinit Sharma94
Hi @Andrew,

When I am trying the above code I am getting this error.User-added image
Could you please help me out to resolve this issue.

Thanks

 
Ajay K DubediAjay K Dubedi
Hi Vinit,

I have made a look for your trouble in the above code. You are getting the error at line no-23,25,27,32.
At line no-23, there is a need to change a bit. For each contact loop, we have also specified the AccountId of that contact.
I have corrected the code. Please try it once.

Replace your all code with this, I am sure it will work.

  
trigger updateAccountEmail on Contact (after insert, after update, after delete) {

    if(trigger.IsAfter && trigger.isInsert)
    {    
        List<Account> accountList = new list<Account>();
//lets use a set , rather than list, as we want the Account once only
        Set <Id> accountIdsSet    = new Set<Id>();
//get a list of all account Ids for contacts being updated
        for(Contact c : trigger.new){
            accountIdsSet.add(c.AccountId);
        }
//create a Map of those Accounts
        Map< Id, Account> accountMap = new Map<Id, Account>([Select Id,Email__c from Account where Id In :accountIdsSet]);

//a map to hold the concatenated emails, keyed by Account id
    Map<Id,String> mapEmails = new Map<Id,String>();
//do a query of all contacts associated with Accounts where a contact has been updated
//so if one contact is updated, inserted or deleted(?) we get all the other contacts and re-write the full email list
    for(Contact c: [SELECT Id, AccountId, Email FROM Contact WHERE AccountId IN :accountIdsSet ORDER BY AccountId])
//note the ORDER by is not really necessary, but may make it easier to trouble shoot
    {
//if key exists, update the existing entry
        if(mapEmails.containsKey(c.AccountId) )
        {
            String emails = mapEmails.get(c.AccountId);
            emails += c.Email+ ';';
            mapEmails.put(c.AccountId,emails);
        }
        else
        {
//create a new Map entry with the initial email address
            mapEmails.put(c.AccountId, c.Email);
        }
    }
//now we have a map with key of Account ID and an associated String of all emails concatenated wiht a semi colon

//so loop the map of actual accounts and use the common key of Account Id to update the Account records
    for (Id aId : accountMap.getKey())
    {
        Account acc = accountMap.get(aId);
        acc.Email__c = mapEmails.get(aId);
//add to a list so we only do the DML once.
        accountList.add(acc);
    }
    update accountList;

}


I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Ajay Dubedi
www.ajaydubedi.com  (http://www.ajaydubedi.com )
Vinit Sharma94Vinit Sharma94

Hi @Ajay K Dubedi

I am getting this issue:-Method does not exist or incorrect signature: void getKey() from the type Map<Id,Account>
Could you please suggest me how can I resolve this problem.
Thanks