+ Start a Discussion
Bryant Daniels 53Bryant Daniels 53 

Update Role on User with Apex

Hello I am trying to update a Role on a user by using Apex currently doing this but receiving attempt to dereference null

UserRole ur = [SELECT Id FROM UserRole Where name = 'CEO'];
        Profile p  = [Select id from Profile where name = 'System Administrator'];
        User u = [Select userrole.id from User Where profileID =: p.id];
        system.debug('ur' + ur);
        system.debug('p' + p);
        system.debug('u' + u);
        
         u.userrole.id = ur.id; 
Best Answer chosen by Bryant Daniels 53
karthikeyan perumalkarthikeyan perumal
Hello 

use below updated code its work with out any issue, 
UserRole ur = [SELECT Id FROM UserRole Where name = 'CEO'];
       Profile p  = [Select id from Profile where name = 'System Administrator'];
       List<User> userFieldUpdate = new List<User>();
      for ( User u : [Select id,UserRoleId  from User Where profileID =: p.id])
      {
          u.UserRoleId  = ur.id;
          userFieldUpdate.add(u);
      }
      
       update userFieldUpdate;
Hope this will help you.
mark Best ANSWER if its works for you. 

Thanks
karthik
 

All Answers

Bryant Daniels 53Bryant Daniels 53
Sorry I forgot the dml

UserRole ur = [SELECT Id FROM UserRole Where name = 'CEO'];
        Profile p  = [Select id from Profile where name = 'System Administrator'];
        User u = [Select userrole.id from User Where profileID =: p.id];
        system.debug('ur' + ur);
        system.debug('p' + p);
        system.debug('u' + u);
        
         u.userrole.id = ur.id; 

update u;
karthikeyan perumalkarthikeyan perumal
Hello 

use below updated code its work with out any issue, 
UserRole ur = [SELECT Id FROM UserRole Where name = 'CEO'];
       Profile p  = [Select id from Profile where name = 'System Administrator'];
       List<User> userFieldUpdate = new List<User>();
      for ( User u : [Select id,UserRoleId  from User Where profileID =: p.id])
      {
          u.UserRoleId  = ur.id;
          userFieldUpdate.add(u);
      }
      
       update userFieldUpdate;
Hope this will help you.
mark Best ANSWER if its works for you. 

Thanks
karthik
 
This was selected as the best answer
Bryant Daniels 53Bryant Daniels 53
Thank you so much