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
Rung41Rung41 

Help with insert trigger after update

I have create 2 trigger to insert a Contact when a new Account record is created andupdate a Contact's Email if a custom field (Company Email) on the Account record is changed. I am not sure how to add a new contact if the Account record already exists and Company Email feild was previously "null" and then update with an email address.

 

Insert Trigger

trigger CompanyEmail on Account (after insert) {

   
  List<Contact> ct = new List <Contact>();
    for (Account newAccount: Trigger.New){
    
        if (newAccount.Company_Email__c != null){
                 ct.add (new Contact(
                     FirstName = 'Account',
                     LastName = 'Email',
                     Email = newAccount.Company_Email__c,
                     AccountId = newAccount.id,
                     OwnerId = '00530000001jaC1'));   
         }
insert ct;  
        }}

 Update trigger:

trigger TriggerWithUpdateEmail on Account (after update) 
    {
        Integer index = 0;       
        for(Account acc : Trigger.New)
            {
                //Check entry criteria
                if(acc.Company_Email__c != Trigger.Old[index].Company_Email__c)                
                    {
                    
                         List<Contact> listCon = [Select Email from Contact where (AccountId =: acc.id) and (FirstName = 'Account')];      
                         for(Contact con : listCon)
                             {
                                 con.Email = acc.Company_Email__c;
                             }
                         update listCon;    
                    }
                index++;
            }
    }

 

Best Answer chosen by Admin (Salesforce Developers) 
Rahul SharmaRahul Sharma

Rung41 wrote:

 

 

  • If an Account already exist but the Company Email field is empty but later on is populated and the there is no Contact with the name "Account Email", create a Contact with the first-name "Account", last-name "Email" with the same email address as the Account field "Company Email".  <---- (this is what I can't figure out) 

 




I updated the trigger to cover the condition, check if it helps.

FYI: I have also avoided a double for loop, since it drastically increases the script statements as it there is a limit on number of script statements.

 

trigger CompanyEmail on Account (after insert, after update)
{
    if(Trigger.isInsert)
    {
        List<Contact> ct = new List <Contact>();
        for (Account newAccount: Trigger.New)
        {
        	//	Insert a contact on account insert with mapping
            if (newAccount.Company_Email__c != null)
            {
                 ct.add (new Contact(
                         FirstName = 'Account',
                         LastName = 'Email',
                         Email = newAccount.Company_Email__c,
                         AccountId = newAccount.id)
                     );   
            }
        }
        if(!ct.isEmpty())
            insert ct; 
    }
    else
    {
    	List<Contact> lstContacttoInsert = new List<Contact>();
    	Set<Id> setAccountIdwithEmail = new Set<Id>();
    	for(Account objAccount: Trigger.new)
    	{
    		if(Trigger.oldMap.get(objAccount.Id).Company_Email__c == null && objAccount.Company_Email__c != null)
            {
            	//	Old value of company email was null and it was assigned a value, so create a contact
            	lstContacttoInsert.add (new Contact(
                         FirstName = 'Account',
                         LastName = 'Email',
                         Email = objAccount.Company_Email__c,
                         AccountId = objAccount.id)
                     );
            }
            if(Trigger.oldMap.get(objAccount.Id).Company_Email__c != Trigger.newMap.get(objAccount.Id).Company_Email__c)
            {
            	//	Old value is updated, so collect the account ids whos contact is tp be updated.
            	setAccountIdwithEmail.add(objAccount.Id);
            }
    	}
    	
    	//	query contacts based on the set of account whose company email field was updated.
    	List<Contact> lstContact = new List<Contact>([Select FirstName, LastName, Email, AccountId, OwnerId from contact where AccountId in: setAccountIdwithEmail]);
        for(Contact objContact: lstContact)
        {
        	//	Modify lstContact with Accounts company email field 
            objContact.Email = Trigger.newMap.get(objContact.AccountId).Company_Email__c;
        }
        if(!lstContact.isEmpty())
            update lstContact;
        if(!lstContacttoInsert.isEmpty())
        	insert lstContacttoInsert;
    }
    
}

 

All Answers

Jeremy_nJeremy_n

So in your After Update trigger, this comes into play inside of your "Check Entry Criteria" block. The code you have there currently should be inside an if statement, and the Else will be for the case you're trying to cover (Company_Email__c used to be null but it isn't now).

if (Trigger.Old[index].Company_Email__c != null)
{
     //your code for updating existing Account contacts here
}
else 
{
     //here you will create some new contacts, just like your After Insert trigger does
}

 

Warning: your After Update trigger is querying once for every record. If you insert too many Accounts, you will hit governor limits. Better to collect Account IDs in a set and make one large query with an ID map than a bunch of individual ones.

 

Jeremy

Rahul SharmaRahul Sharma

Follow the best practices by bulkifying your records.

* Never update or query inside a for loop.

 

I didn't actually get what you are trying to do,

as per my understanding i think you want to update the contact's email only if Company Email of Account is changed.

 

Also you can club both triggers in one and pushing your logic inside event isInsert and isUpdate.

I modified the code for you:

trigger CompanyEmail on Account (after insert, after update)
{
    if(Trigger.isInsert) 
    {
        List<Contact> ct = new List <Contact>();
        for (Account newAccount: Trigger.New)
        {
            if (newAccount.Company_Email__c != null)
            {
                 ct.add (new Contact(
                         FirstName = 'Account',
                         LastName = 'Email',
                         Email = newAccount.Company_Email__c,
                         AccountId = newAccount.id,
                         OwnerId = '00530000001jaC1')
                     );   
            }
        }
        if(!ct.isEmpty())
            insert ct; 
    }
    else
    {
        List<Contact> lstContact = new List<Contact>();
        for(Contact objContact: [Select FirstName, LastName, Email, AccountId, OwnerId from contact where AccountId in: Trigger.new])
        {
            if(Trigger.newMap.get(objContact.AccountId).Company_Email__c != null && Trigger.oldMap.get(objContact.AccountId).Company_Email__c != Trigger.newMap.get(objContact.AccountId).Company_Email__c)
            {
                objContact.Email = Trigger.newMap.get(objContact.AccountId).Company_Email__c;
                lstContact.add(objContact);
            }
        }
        if(!lstContact.isEmpty())
            update lstContact;
    }
}

Let me know if you face any problem.

Rung41Rung41

Thanks for the reply and code modification.  I knew there was a way to combine triggers..just not so good at it yet.

 

What I am trying to do is the following:

 

  • If a new Account is created and the field "Company Email" is populated, create an Contact with the first-name "Account", last-name "Email" with the same email address as the Account field "Company Email".

 

  • If an Account already exist but the Company Email field is empty but later on is populated and the there is no Contact with the name "Account Email", create a Contact with the first-name "Account", last-name "Email" with the same email address as the Account field "Company Email".  <---- (this is what I can't figure out)

 

  • If an Account already  and the Contact "Account Email" exists, and the Company Email field is updated, also update the email field on the Contact "Account Email"
Rahul SharmaRahul Sharma

Rung41 wrote:

 

 

  • If an Account already exist but the Company Email field is empty but later on is populated and the there is no Contact with the name "Account Email", create a Contact with the first-name "Account", last-name "Email" with the same email address as the Account field "Company Email".  <---- (this is what I can't figure out) 

 




I updated the trigger to cover the condition, check if it helps.

FYI: I have also avoided a double for loop, since it drastically increases the script statements as it there is a limit on number of script statements.

 

trigger CompanyEmail on Account (after insert, after update)
{
    if(Trigger.isInsert)
    {
        List<Contact> ct = new List <Contact>();
        for (Account newAccount: Trigger.New)
        {
        	//	Insert a contact on account insert with mapping
            if (newAccount.Company_Email__c != null)
            {
                 ct.add (new Contact(
                         FirstName = 'Account',
                         LastName = 'Email',
                         Email = newAccount.Company_Email__c,
                         AccountId = newAccount.id)
                     );   
            }
        }
        if(!ct.isEmpty())
            insert ct; 
    }
    else
    {
    	List<Contact> lstContacttoInsert = new List<Contact>();
    	Set<Id> setAccountIdwithEmail = new Set<Id>();
    	for(Account objAccount: Trigger.new)
    	{
    		if(Trigger.oldMap.get(objAccount.Id).Company_Email__c == null && objAccount.Company_Email__c != null)
            {
            	//	Old value of company email was null and it was assigned a value, so create a contact
            	lstContacttoInsert.add (new Contact(
                         FirstName = 'Account',
                         LastName = 'Email',
                         Email = objAccount.Company_Email__c,
                         AccountId = objAccount.id)
                     );
            }
            if(Trigger.oldMap.get(objAccount.Id).Company_Email__c != Trigger.newMap.get(objAccount.Id).Company_Email__c)
            {
            	//	Old value is updated, so collect the account ids whos contact is tp be updated.
            	setAccountIdwithEmail.add(objAccount.Id);
            }
    	}
    	
    	//	query contacts based on the set of account whose company email field was updated.
    	List<Contact> lstContact = new List<Contact>([Select FirstName, LastName, Email, AccountId, OwnerId from contact where AccountId in: setAccountIdwithEmail]);
        for(Contact objContact: lstContact)
        {
        	//	Modify lstContact with Accounts company email field 
            objContact.Email = Trigger.newMap.get(objContact.AccountId).Company_Email__c;
        }
        if(!lstContact.isEmpty())
            update lstContact;
        if(!lstContacttoInsert.isEmpty())
        	insert lstContacttoInsert;
    }
    
}

 

This was selected as the best answer
Rung41Rung41

Thanks for the help...I have started writting a test method for the trigger but once again I am stuck at the "update portion". If you could point me in the right direction, I would greatly appreciate it. On a side note...I did sign up for Apex class in hopes to learn and instead of asking.

 

public class testCompanyEmailEntry {
static testmethod void CompanyEmail (){ 
    test.startTest();
             // Insert a new Account to test        
 Account ant = New Account(
                
                Name = 'TestAccountA', 
                Company_Email__c = 'account@bfr.com',
                BillingStreet = '123 Main St',
                BillingCity = 'Anywhere',
                BillingState = 'CA',
                BillingPostalCode = '12345',
                Market_Segment__c ='Apartment Community'
                );  
 insert ant;
 
  List<Contact> ct = new List <Contact>();
             
         if (ant.Company_Email__c != null){
                 ct.add (new Contact(
                     FirstName = 'Account',
                     LastName = 'Email',
                     Email = ant.Company_Email__c,
                     AccountId = ant.id,
                     OwnerId = '00530000001jaC1'));   
         
         
                 
                // insert Contact 
                insert ct;
               
                //update ct;  
                
               test.stopTest();     
                  
            }   }}

 

Rahul SharmaRahul Sharma

Hi Rung41,

Good to know that you would join the classes.

I have modified the test method to cover the trigger. check if it helps, if not let me know what didn't worked.

public class testCompanyEmailEntry 
{
	static testmethod void CompanyEmail ()
	{ 
		test.startTest();
		
		//	Cover insert case
		Account objAccount = New Account(
									Name = 'TestAccountA1', 
									Company_Email__c = 'account@bfr.com',
									BillingStreet = '123 Main St',
									BillingCity = 'Anywhere',
									BillingState = 'CA',
									BillingPostalCode = '12345',
									Market_Segment__c ='Apartment Community'
								);  
		insert objAccount;
		
		//	Cover Update case to cover update case
		Account objAccount1 = New Account(
											Name = 'TestAccountA',
											BillingStreet = '123 Main St',
											BillingCity = 'Anywhere',
											BillingState = 'CA',
											BillingPostalCode = '12345',
											Market_Segment__c ='Apartment Community'
										);  
		insert objAccount1;


		Contact ct  = new Contact(
									FirstName = 'Account',
									LastName = 'Email',
									Email = objAccount1.Company_Email__c,
									AccountId = objAccount1.id,
									OwnerId = '00530000001jaC1'
								);
		insert ct;
		
		//	Previously Acount Company email was null now it has a value so it will insert a contact and also it will update the existing contacts
		objAccount1.Company_Email__c = 'account@bfr.com';
		update objAccount1;
	}
}