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
Pravin ShewalePravin Shewale 

whenever contact is created or updated update email based on Contact Last Name

I tried the below trigger code but, getting  unexpected exception can anyone help.

trigger UpdateEmail on Contact (after insert, after update) {
    Set <String> AccId = New Set <String> (); 
    For (Contact con: Trigger.new){ 
        if (con.AccountId != Null ){ 
        AccId.add(con.AccountId); 
        } 
    } 
    List<Contact> con = [SELECT Id,LastName, Email, Account.Id FROM Contact WHERE Account.Id != null];
    List<Contact> newCon = new List<Contact>();
    for(Contact con: Trigger.new){
        Contact Cont = new Contact();
        Cont.Id = con.AccountId;
        Cont.Email = con.lastname+'@test.com';
        System.debug('Test'+Cont.Id);
        newCon.add(Cont);
    }
    update newCon;

}
 

Dushyant SonwarDushyant Sonwar
This will be on before event as you want to update the same object that you are writing trigger
trigger UpdateEmail on Contact (before insert, before update) {
    Set <String> AccId = New Set <String> (); 
    For (Contact con: Trigger.new){ 
        if(trigger.isInsert){
			Cont.Email = con.lastname+'@test.com';
		}
		if(trigger.isUpdate){
			if(itigger.oldMap.get(con.id).Email != con.Email){
				Cont.Email = con.lastname+'@test.com';
			}
		}
    } 

}

 
Omar Rajab 94Omar Rajab 94

Hi Pravin,
You should use Before Triggers for you Use Case. Try the Code below: 
 

trigger UpdateEmail on Contact (before insert, before update) {

 switch on Trigger.OperationType {
        when BEFORE_UPDATE, BEFORE_INSERT {
          for (Contact con: Trigger.new){ 
	        if(String.isNotBlank(con.Email) {
                  con.Email = con.lastname+'@test.com';

                  }
     		}
          }
      }
}

 

Regards,
Omar

Pravin Shewale 8Pravin Shewale 8

Thanks you both..!

Issue Resolved.

Omar Rajab 94Omar Rajab 94
Could you please mark which answer was the best for you, as the best answer?

regards
Omar