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
fiona gentryfiona gentry 

Anonymous apex to update Profile Name

Dear Folks,

Written a anonymous apex to update the user's profile name from Profile1 to Profile 2,i see anonymous apex ran successfully ,but i dont see the Profile.name got changed,any idea what is going wrong with below code
List<User> lstUsers = new List<User>();

for(User userToChangePermission : [SELECT ID,firstname,lastname,username,isActive,Profile.Name FROM User WHERE Profile.Name = 'Profile1' LIMIT 100 ])

{userToChangePermission.Profile.Name = 'Profile2';
lstUsers.Add(userToChangePermission);}

if(!lstUsers.isEmpty())
{
System.debug(lstUsers);
Update lstUsers;    
}

Your help is appreciated

Regards
Fiona
 
Best Answer chosen by fiona gentry
AnkaiahAnkaiah (Salesforce Developers) 
Hi Fiona,

try with below code. You need to assign profile Id instead of Name.
List<User> lstUsers = new List<User>();
Profile prfid = [select id from profile where Name='Profile2'];

for(User userToChangePermission : [SELECT ID,firstname,lastname,username,isActive,Profile.Name,profileId FROM User WHERE Profile.Name = 'Profile1' LIMIT 100 ])

{userToChangePermission.profileId = prfid;
lstUsers.Add(userToChangePermission);}

if(!lstUsers.isEmpty())
{
Update lstUsers;    
}

System.debug('lstUsers=='+lstUsers);

If this helps, Please mark it as best answer.

Thanks!!

All Answers

AnkaiahAnkaiah (Salesforce Developers) 
Hi Fiona,

try with below code. You need to assign profile Id instead of Name.
List<User> lstUsers = new List<User>();
Profile prfid = [select id from profile where Name='Profile2'];

for(User userToChangePermission : [SELECT ID,firstname,lastname,username,isActive,Profile.Name,profileId FROM User WHERE Profile.Name = 'Profile1' LIMIT 100 ])

{userToChangePermission.profileId = prfid;
lstUsers.Add(userToChangePermission);}

if(!lstUsers.isEmpty())
{
Update lstUsers;    
}

System.debug('lstUsers=='+lstUsers);

If this helps, Please mark it as best answer.

Thanks!!
This was selected as the best answer
sam ramysam ramy
Once you complete the basic preparation for SAP Certified Application Associate (https://www.dumpscollection.com/C_S4CFI_2208-exam.html) - SAP Ariba Supply Chain Collaboration exam, you need to revise the SAP syllabus and make sure that you are able to answer real C_ARSCC_2208 exam questions.