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
Suraj AdeSuraj Ade 

How to write apex script for transferring all the users of one profile to other Profile?

Best Answer chosen by Suraj Ade
Maharajan CMaharajan C
Hi Suraj,

Try the below script in anonymous window on developer on and let me know if there is any error:
 
Id ProfileX = '00e0K000001kzB4';  // user
Id ProfileY = '00e28000000HnvN';
List<user> users = [Select Id, ProfileId from user where ProfileId = : ProfileX];
for(user u : users)
{
	u.ProfileId = ProfileY;
}
try{
	update users;
    system.debug(' === Success === ');
}
catch(Exception ex){
	system.debug( ' Exception ==> ' + ex.getMessage() );
}


Thanks,
Maharajan.C

All Answers

SUCHARITA MONDALSUCHARITA MONDAL

Hi Suraj,

This is possible by exposing Metadata API, (give it a try)

Check the link (will give some inputs)
https://developer.salesforce.com/forums/?id=906F00000009BD8IAM
https://salesforce.stackexchange.com/questions/16299/updating-profile-using-metadata/16310

Thanks,
Sucharita

Suraj AdeSuraj Ade
Hi Sucharita,
Thanks for your reply. I have two profiles lets say x and y. I want to move all the users of profile x to profile y. How can it be achieved with the help of profile IDs.?

Thanks,
Suraj
Maharajan CMaharajan C
Hi Suraj,

Try the below script in anonymous window on developer on and let me know if there is any error:
 
Id ProfileX = '00e0K000001kzB4';  // user
Id ProfileY = '00e28000000HnvN';
List<user> users = [Select Id, ProfileId from user where ProfileId = : ProfileX];
for(user u : users)
{
	u.ProfileId = ProfileY;
}
try{
	update users;
    system.debug(' === Success === ');
}
catch(Exception ex){
	system.debug( ' Exception ==> ' + ex.getMessage() );
}


Thanks,
Maharajan.C
This was selected as the best answer
Suraj AdeSuraj Ade
Hi Maharajan.C

Thanks for your help but I want to move multiple or all users of one profile to other not just single. How that can be done?


Thanks,
Suraj 
Maharajan CMaharajan C
The code will work for multiple users.  But for single profile transfer ( one profile to another profule) .

ProfileX  ==>  from profile Id.
ProfileY  ==> To profile Id 

Thanks,
Maharajan.C
Suraj AdeSuraj Ade
Hi Maharajan C, 

Thanks for your help. Now I am trying to rename the the profile using following code but getting DML exception. Following is my code.


Id ProfileX = '00e0K000001kzB4';  // profile id of profile to Rename
String ProfileName = 'Y';  
Profile Prof = [Select Name from Profile where Id = : ProfileX];
    
Prof.Name = ProfileName ;

try{
    update Prof;
    system.debug(' === Success === ');
}
catch(Exception ex){
    system.debug( ' Exception ==> ' + ex.getMessage() );
}



Thanks,
Suraj