• Vinit Sharma94
  • NEWBIE
  • 0 Points
  • Member since 2019

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 2
    Replies

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;
    }

}

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;
    }

}