Print this page

FIELD_INTEGRITY_EXCEPTION, updating profileid via apex

Knowledge Article Number 000199523
Description Update works fine if old profile license is same as new profile license.

----- Sample code to replicate the issue----- 

list<user> users = [SELECT Id,firstname, lastname, IsActive,ProfileId,UserType FROM User where profileId in :[select id from Profile where name = '<chatter user profile>']]; // these users have different license, suppose "XYZ License" 
Profile p = [select id from profile where name='Standard Platform User']; // And these users have different license, suppose "ABC License" 
for(User u:users){ 
 u.profileId= p.id; 

update users; 

------------------------------------------------- 

Result : FIELD_INTEGRITY_EXCEPTION, You can only reassign this user to a profile of the current license.: [ProfileId]. 

-------Sample code where update works fine for same license------- 

list<user> users = [SELECT Id,firstname, lastname, IsActive,ProfileId,UserType FROM User where profileId in :[select id from Profile where name = 'Standard User']]; // these users have "salesforce License" 
Profile p = [select id from profile where name='Standard Platform User'];// these users have "salesforce License" 
for(User u:users){ 
u.profileId= p.id; 

update users; 

---------------------------------------- 

Result : updated successfully 
Resolution This is working as designed, as User Profile will be dependent on User License (profile field is dependent on User License Field) so the available profiles will be dependent on selected User License of that particular user. Actually being able to modify that through code would open up a whole new set of security risks. 

To workaround this issue,
  • Clone the user via apex. 
  • Take it in list<user> 
  • Inactive the old user which has been cloned 
  • Insert new user, which are exist in list. 
 
-------Sample code to workaround the issue-------
list<user> users = [SELECT Id,firstname, lastname, IsActive,ProfileId,UserType FROM User where profileId in :[select id from Profile where name = 'portal']]; // these users have different license, suppose "XYZ License" 
Profile p = [select id from profile where name='community']; // And these users have different license, suppose "ABC License" 
for(User u:users){ 
u.isactive = false; 
update users; 
list<user> newUserList = new list<user>(); 
for(User u1:users){ 
user NewUser = new user(); 
NewUser.allrequiredFields = u1.allrequiredFields; 
// put all required fields 
newUserList.add(NewUser); 
insert newUserList; 




promote demote