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
vcvenureddyvcvenureddy 

System.SObjectException: Field is not writeable: User.ProfileId

Hi ,

Could you please help me on below error,

System.SObjectException: Field is not writeable: User.ProfileId

thanks in advance.
venu
vcvenureddyvcvenureddy
Here we are trying to create portal user.

thanks.
vcvenureddyvcvenureddy
public PageReference saveUser() {

        PageReference pr;
        SavePoint sp = Database.setSavepoint();
        

        //System.debug('u: ' + u);
        if ( u.Id == null ) {
            system.debug('If LOOP');
            if(test.IsRunningTest()){
                u=[select id,FirstName,UserName,ContactId,Email,CommunityNickname from User where isActive = true limit 1];
              //  SenderName = 'Test Name';
                //contu = [select id,Name from Contact limit 1];//u.ContactId; 
            }
            if(!test.IsRunningTest()){
                contu = createContact(u, currentAccount.Id);
            }
            //System.debug('FM: new Contact: '+contu );
            String alias = 'a' + u.FirstName;
            if ( alias.length() > 8 ) {
                alias = alias.substring(0, 8);
            }
           // u = [select id,profileid from user where id =:userinfo.getuserid()];
            cont = [select id,Email,MobilePhone,Phone from contact where id = '00356000001gCa0'];
            u.CommunityNickname = u.FirstName + '_' + cont.Id;
            System.debug('vcr---cont id---'+cont.Id);
            System.debug('vcr---profileId--'+profileId);
            
            u.Alias = alias; 
            u.isActive = true;
            u.Email = cont.Email;
            System.debug('cont.:'+cont.Email);
            u.Phone = cont.Phone;
            u.MobilePhone = cont.MobilePhone;
            u.Username = u.UserName;
            //********** MOdified by Yash Mehta & Manjunath **************//
            //************** Check to make sure Nickname length is not greater than 40 chars ********//
            //u.CommunityNickname = u.Email+Integer.ValueOf((Math.random() * 10000));
            string rand = String.valueof(u.Email+Integer.ValueOf((Math.random() * 10000)));
            system.debug('>>>>>>'+rand);
            if(rand.length()>40)
            {           
                u.CommunityNickname = rand.substring(0,39);
                 system.debug('If.....'+u.CommunityNickname);
            }  
            else
            {
               u.CommunityNickname = u.Email+Integer.ValueOf((Math.random() * 10000));
               system.debug('else.....'+u.CommunityNickname);
            }
            
            u.TimeZoneSidKey = 'America/Chicago';
            u.LocaleSidKey = 'en_US';
            u.EmailEncodingKey = 'ISO-8859-1';
            u.LanguageLocaleKey = 'en_US';
            try{
                u.ContactId = cont.Id;
            }catch(Exception e){}
          //  u.SenderName = SenderName;
            //System.debug('******TCC Default Branch Name:' + contu.TCC_Default_Branch__r.Name);
            //System.debug('u.Contact.TCC_Default_Branch__c:' +u.Contact.TCC_Default_Branch__c);
            // System.debug('****u.Contact.TCC_Default_Branch****:' +u.Contact.TCC_Default_Branch__r.Name);
            // u.SenderName= 'testing4';
            // u.Division= defaultBranch;
             
           // u.TCCTest__c = u.TCCContact__c;
              
            //System.debug('*******u.Division:' +u.Division);
            System.debug('*******vcr--*******' +u.ContactId );
            u.UserPermissionsChatterAnswersUser = true;
            u.ProfileId = profileId;
            if ( profileId != (ID) this.settings.Portal_Technician_Profile_Id__c ) {
                u.UserRoleId =  
                    [select Id
                    from UserRole 
                    where PortalRole = :profileIdToPortalRoleMap.get(profileId)
                        and PortalAccountId = :this.currentAccount.Id].Id;
            }
            //System.debug('----role id'+u.UserRoleId);
            //System.debug('u.UserRoleId: ' + u.UserRoleId);
            //insert u;
            
            //createUser(JSON.serialize(u));
            serializedUser = JSON.serialize(u);
            this.alertPrefVip = this.alertPrefVip.clone(false,true,false,false);
            this.alertPrefRegular= this.alertPrefRegular.clone(false,true,false,false);
            this.alertPrefVip.TCC_Contact__c = contu.Id;
            this.alertPrefRegular.TCC_Contact__c = contu.Id;
            insert new List<TCC_Alert_Preference__c>{this.alertPrefVip, this.alertPrefRegular};
            pr = null;
/*
            pr = Page.TCCManageUsers;
            pr.getParameters().put('confirm', 'userInsert');
            addSuccessMessage('User Created.');
            this.users = null;
    */        
            
        } else {
            system.debug('Else If LOOP');
            //update u;
            licenseError = false;
            
            //System.debug('u.ProfileId------'+u.ProfileId);
            //System.debug('ProfileId------'+ProfileId);
            //System.debug('settings ProfileId------'+this.settings.Portal_Technician_Profile_Id__c);
            if ( u.ProfileId != profileId ) {
                // Set User Role based on Profile ID
                if( profileId == (ID) this.settings.Portal_Technician_Profile_Id__c ||
                    u.ProfileId == (ID) this.settings.Portal_Technician_Profile_Id__c )
                {
                    Map<ID,String> profileNames = new Map<Id,String> ();
                    for(TCC_Contractor_Profile__c cp : [Select Profile_Id__c, Name from TCC_Contractor_Profile__c where Profile_Id__c=:profileId or Profile_Id__c=:((String)u.ProfileId).subString(0,15)])
                    {
                        profileNames.put(cp.Profile_Id__c, cp.Name);
                    }
                    //System.debug('ProfileIdsssss------'+profileNames);
                    /*
                    addErrorMessage('Oops! Due to the account type, a user can’t be changed from '+profileNames.get(u.profileId)+' to '+(profileNames.get(profileId)== null ? 'None' : profileNames.get(profileId) )+ '. To make this change please contact a Honeywell administrator by clicking "Help" at the top of the page.');
                    */
                    licenseError = true;
                    //return null;
                }
                roleId = u.UserRoleId;
                if ( profileId != (ID) this.settings.Portal_Technician_Profile_Id__c ) {
                    roleId = 
                        [select Id 
                        from UserRole 
                        where PortalRole = :profileIdToPortalRoleMap.get(profileId)
                            and PortalAccountId = :this.currentAccount.Id].Id;
                    if ( roleId != null ) {
                        u.UserRoleId = roleId;
                    }
                }
                //System.debug('roleId: ' + roleId);
                //updateUserProfile();
            }

            updateContact(u.ContactId, cont.TCC_Qualifications__c,branchId);
            upsert new List<TCC_Alert_Preference__c>{this.alertPrefVip, this.alertPrefRegular};
            pr = null;
            String retUrl = ApexPages.currentPage().getParameters().get('retUrl');
            
        }
        

 u.ProfileId = profileId;
this is the place where we are facing issue.

Thankyou.
vcvenureddyvcvenureddy
Hi Amit,

This is working fine when we remove "with sahring" for class.
Thankyou.
vcvenureddyvcvenureddy
Hi Amit,

This is not solved yet.

We need "with sahring" for class, why because we have different levels of access on users.

If you have any solution for this without removing sharing on class?

Thank you. 
 
Andries.NeyensAndries.Neyens
Did you find a solution in the meantime?
We have a simular situation, and the weird thing is, that it used to work, and now we receive the same error.
Without sharing is solving it, but I want to understand what I changed on profile level or what was changed by the API (running on 36)
benburbbenburb
I'm having the same issue, and it just started today on code that hasn't been touched in ages. Boilerplate Community User creation code...
vcvenureddyvcvenureddy
change the version to lower...that works...
Jon Snow 18Jon Snow 18
I faced the same type of issue. Without changing any code not able to create a user via APEX. In my case, I reduce API version. So API version lesser than 34 (<= 33) should fix this issue.