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 

Helo with Trigger please. Almost there but not quite

I have created a trigger that creates a Contact called "Accunt Email" if a new Account is created and a custom field called "Company Email" is populated with an email address.

 

I have trigger working on "after insert" but when I try to add "after update" it duplicates the contact record. I'm not sure how to include the "after update" without creating duplicte contacts or how update the email address on the Contact record if the email address on the Account page is modified.

 

Thanks!

 

trigger CompanyEmail on Account (after insert, after update) {

   
  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;  
        }
      if (Trigger.isUpdate) {
        List<Contact> cnt = [SELECT id FROM Contact WHERE Firstname = 'Account'];
       for(Account olduAccount : trigger.old){
            
              cnt.add (new Contact(
                    
                   
                    Email = olduAccount.Company_Email__c));
           {
    update cnt;
               {
                
      
 
 }}}}}

 

NzgonNzgon

For update event you have available list with old values for records.

 

Use Trigger.Old list and compare with Trigger.New in order to determine changes.

 

 

Nash