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
Rakhi B 10Rakhi B 10 

contact firstname update user name aslo update using trigger in contact object

Ajay K DubediAjay K Dubedi

Hi Rakhi,

Please try the below code for update username in contact.

public class ContactUpdateWithUser {
    public static void isAccount(List<Contact> conList){
        String userName = UserInfo.getName();
        system.debug('User Name ------------>'+UserName);
        if(conList != NULL){
            Map<Id,User> accMap = new Map<Id,User>([SELECT id,Name FROM User WHERE Name = : userName ]);
            for(contact cont : conList)
            {
                cont.FirstName = accMap.get(cont.OwnerId).Name;
            }
            try{
                update accMap.Values();
            }catch(DMLException e){
                system.debug(e.getMessage());
            }
        }
        
    }
}
Trigger Class
trigger TestAccountContact on Contact (before insert , before update) {
    if((trigger.IsInsert && trigger.isBefore) || (trigger.isBefore && trigger.isUpdate)){
  ContactUpdateWithUser.isAccount(trigger.new);
 }
  
}

Please make it best if it helps you.


Thanks
Ajay Dubedi
Jithesh VasudevanJithesh Vasudevan
Hi Rakhi,

Trigger contactUpdate on Contact(Before update){
   for(Interger i=0; i<trigger.new.size(); i++)
    {
      if(trigger.new[i].FirstName != trigger.old[i].FirstName){
        trigger.new[i].OwnerId = '<Desired OwnerId>';
      }
   }
}