[SalesForce] Can’t change a user’s profile

I have a method that changes a user's profile. It works well when the old and the new profiles belong to the same user licence, but when they're from different user licences, it throws an error.

Here's my code:

public static void changeProfile(ID userId, ID profileId){
    User u=[select id, name, contactid, profileId from User where id=:userId];
    Profile p=[select id, name from profile where id=:profileId];
    u.ProfileId=p.Id; 
    update u;
}

And this is the error:

System.DmlException: Update failed. First exception on row 0 with id 0051I000000aVQbQAM; first error: FIELD_INTEGRITY_EXCEPTION, You can only assign profiles that are compatible with the user's license. For a list of compatible licenses and profiles, see the Salesforce Help.: [ProfileId]

How can I solve this?

I'm working with communities, by the way, and the profiles that I'm working with belong to Customer Portal Manager Licence and Customer Community Licence.

Best Answer

Edit: The below answer is still mostly true, but there are exceptions. You can, for example, change a Chatter user to a Salesforce user licence, but you cannot later downgrade that user back to a Chatter user.


You can't change the user's license type after creation, therefore you cannot change their profile to a new license type than what they had at creation. This restriction is probably in place because changing the user's license type might cause orphan data or break other database constraints. For now, you need to create new users. And yes, you will have lots of inactive users, but they don't count against your license limits. Consider setting their usernames to nonsense values when you deactivate them so they don't conflict with real email addresses.

Related Topic