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
Siva SakthiSiva Sakthi 

Unable to update users object fields via apex code

Hi ,

I am trying to insert the user via apex its working fine. when we updating the user via apex code its causing error like username must unique. but we just change the user name, first name, last name or email how to achive this any sample code how to solve this. Please guide to solve this.

Advance Thanks,
Maheshwar.
ManojjenaManojjena
Hi Maheswar ,

Use below code it will work .
Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator']; 
        
        User usr= new User(Alias = 'sys', Email='systemadmin@testorg.com', 
                          EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
                          LocaleSidKey='en_US', ProfileId = p.Id, 
                          TimeZoneSidKey='America/Los_Angeles', UserName='sysadmintest@ss.com');

Insert usr;

   

 
Ajay Nagar 7Ajay Nagar 7
Hi Maheshwar,

Before updating username,email make sure there is no duplicate user exist with same details you are saving.

Thanks
Ajay
Siva SakthiSiva Sakthi
Hi,

Using this below code able to create the user successfully.' I want to get the newly inserted user Id Immediately' .Once again we put the query to get a user id or Is any way to get the user id. how to get this . Using Userinfo.getUserId() we can get current loged in user. Please guide me to achive this .
Sai GuptaSai Gupta

Hi

You can try this to change the username. Hope this will help you.

list<user> us = [SELECT ID, username, name FROM user WHERE profile.name != 'System Administrator' and username like '%abc.com'];
for(user u: us){
    if(u.username.contains('@abc.com')){
        u.username = u.username.replace('@abc.com', '@abc.com.xyz');
    }
}
system.debug('User>>>>' + us);
update us;