+ Start a Discussion
Atul Kumar 82Atul Kumar 82 

How to write a trigger on contact object where if phone number is not equal to blank then update the Name with a string as a contact name updated?

Khan AnasKhan Anas (Salesforce Developers) 
Hi Atul,

I trust you are doing very well.

Below is the sample code. Kindly modify the code as per your requirement.
 
trigger ContactName on Contact (before insert, before update) {
    
    for(Contact a : Trigger.new){
        if (a.Phone != Null) {
            a.LastName = 'Khan';
        }   
    } 
}

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in future.

Thanks and Regards,
Khan Anas
prateek jainprateek jain
Hi Atul,
Please find the code below  which will append "MobilePhone" field of the contact  to  the contact Name. I hope below  code will help you . please let me know if you find any issue and if it helps you please mark it as best answer

trigger CommunityContactAns on Contact (before insert,before update) {
  
List<Contact>ContactListTobeupdated=new  List<Contact>();  
    for(Contact con:Trigger.new){
       
        if(con.MobilePhone!=null){
            con.LastName=con.LastName+con.MobilePhone;
            ContactListTobeupdated.add(con);
        }
    }
    

}
Akshay_DhimanAkshay_Dhiman
Hi Atul,

Here is a solution to your Problem.
 
Trigger
        
trigger ConcatenateAccNameTrigger on Contact (before insert, before update,after delete) {
    if((Trigger.isBefore && (Trigger.isInsert || Trigger.isUpdate)){ 
        NameUpdatedTriggerHandler.updateContactName(trigger.new);
    }
    if(Trigger.isDelete && Trigger.isafter){
        NameUpdatedTriggerHandler.updateContactName(trigger.old);
    }
}


Trigger_Handler
    
public with sharing class NameUpdatedTriggerHandler{
    public static void updateContactName(List<Contact> lstContact){ // lstContact has contain list of Contacts 
        
        for(Contact con : lstContact){
            if(con.Phone !=null){
                con.LastName= con.LastName + 'Updated';             // Append 'Updated' in a lastName When Phone is not equal to null
            }
        }
        for(Contact con : lstContact){
            if(con.Phone == null){
                con.LastName= con.LastName.remove('Updated');         // remove 'Updated' When Phone is equal to null
            }
        }
    }
}


I hope it will help you.
Please select this as Best Answer so that other's also get help from this.
 
Thank You
Akshay