[SalesForce] There was an error in registering a user in site Charger_Community. The error message is: portal account owner must have a role

I am registering an account in renault community, but i am getting the following error message, even though the portal account owner has a role assigned.

There was an error in registering a user in site Renault_Community.
The error message is: portal account owner must have a role.

Workaround:
All the existing asked questions was mentioning to assign to a role in test class. But the problem is with the line in this class,i hope so

String userId = Site.createPortalUser(u, accountId, password);

Please suggest a solution to avoid this error.

global without sharing class LightningSelfRegisterController {

    public LightningSelfRegisterController() {

    }

    private static boolean isValidPassword(String password, String confirmPassword) {
        return password == confirmPassword;
    }

    private static boolean siteAsContainerEnabled(Id networkId) {
        Auth.AuthConfiguration authConfig = new Auth.AuthConfiguration(networkId,'');
        return authConfig.isCommunityUsingSiteAsContainer();
    }

    private static void validatePassword(User u, String password, String confirmPassword) {
        Site.validatePassword(u, password, confirmPassword);
        return;
    }     

    @AuraEnabled
    public static String selfRegister(String firstname ,String lastname, String email, 
                                      String password, String confirmPassword, String accountId, 
                                      String regConfirmUrl, String extraFields, String startUrl, 
                                      Boolean includePassword) {

          Account existedAccount;
          System.debug('selfRegister');
          Savepoint sp = null;
          try {
              sp = Database.setSavepoint();

              System.debug('firstname' +firstname);
              System.debug('lastname' +lastname);
              System.debug('email' +email);
              System.debug('accountId' +accountId);
              System.debug('regConfirmUr' +regConfirmUrl);
              if (firstname == null || String.isEmpty(firstname)) {
                  return Label.Registration_First_name_cannot_be_empty;
              }

              if (lastname == null || String.isEmpty(lastname)) {
                  return Label.Registration_Last_name_cannot_be_empty;
              }

              if (email == null || String.isEmpty(email)) {
                  return Label.Registration_Username_cannot_be_empty;
              }       

              User u = new User();
              u.Username = email.trim();
              u.put('Email',email.trim());

              u.FirstName = firstname.trim();
              u.LastName = lastname.trim();

              String networkId = Network.getNetworkId();

              // If using site to host the community the user should not hit s1 after logging in from mobile.
              if(networkId != null && siteAsContainerEnabled(networkId)) {
                  u.put('UserPreferencesHideS1BrowserUI',true);
              }

              String nickname = ((firstname != null && firstname.length() > 0) ? firstname.substring(0,1) : '' ) + lastname.substring(0,1);
              nickname += String.valueOf(Crypto.getRandomInteger()).substring(1,7);
              u.put('CommunityNickname', nickname);

              if (extraFields != null) {
                  List<Object> extraFieldsList = (List<Object>) JSON.deserializeUntyped(extraFields);        
                  for (Object thisFieldObject : extraFieldsList) {
                      Map<String,Object> thisField = (Map<String,Object>) thisFieldObject;
                      Schema.SObjectField sof = Schema.SObjectType.User.fields.getMap().get((String) thisField.get('fieldPath'));
                      u.put(sof, thisField.get('value'));
                  }
              }

              // Checks for Duplicate Community Nickname already used
              List < User > userList = [Select Id from User Where CommunityNickname = : u.CommunityNickname Limit 1];
              if (userList.size() > 0) {
                  return Label.Nickname_in_Use;
              }

              // Checks for Duplicate Email address already used
              userList = [Select Id from User Where Username = : email Limit 1];
              if (userList.size() > 0) {
                  return Label.Duplicate_Email_Message;
              }

              if (includePassword) {    
                  if (!isValidPassword(password, confirmPassword)) {
                      return Label.site.passwords_dont_match;
                  }
                  validatePassword(u, password, confirmPassword);
              }
              else {
                  password = null;
              }

              // Set Community User Avatar Picture to Public view access (default is Members)
              u.UserPreferencesShowProfilePicToGuestUsers = true;

              // Look for Person Account with the same Email Address
              List < Account > accList = [Select Id, FirstName, LastName, Country__c, Language__pc, PersonContactId From Account Where PersonEmail = : u.email Limit 1];
              if (accList.size() > 0) {
                  existedAccount = accList.get(0);
                  accountId = existedAccount.id;               
              }

              // Update Account's name if Person Account already exist and User is being created by the customer
              if (existedAccount != null && existedAccount.FirstName != null && existedAccount.LastName != null && (existedAccount.FirstName.trim() != u.FirstName.trim() || existedAccount.LastName.trim() != u.LastName.trim())) {

                  Contact conToUpdate = new Contact(Id = existedAccount.PersonContactId);
                  conToUpdate.FirstName = u.FirstName;
                  conToUpdate.LastName = u.LastName;
                  update conToUpdate;
                  System.debug('conToUpdate'+conToUpdate);
              }   

              // Hardcode English US for renault & nissan;
              u.LanguageLocaleKey = 'en_US';

              System.debug('#@####' + u + ' ' + accountId + '!' );
              // lastName is a required field on user, but if it isn't specified, we'll default it to the username
              String userId = Site.createPortalUser(u, accountId, password);    
              System.debug('userId' + userId);
              // Hardcode English US for renault & nissan;
              User user = [SELECT ContactId FROM User WHERE Id = : userId];
              if (user != null) {
                  Contact contact = [SELECT AccountId FROM Contact WHERE Id = : user.ContactId LIMIT 1];                
                  Account account = [SELECT Country__c, Language__pc FROM Account WHERE Id = : contact.AccountId LIMIT 1];

                  if (account != null) {   
                      List < Country__c > countryList = [SELECT Id FROM Country__c WHERE ISO_Code__c = 'US' LIMIT 1];
                      account.Country__c = countryList.get(0).id;
                      account.Language__pc = 'English (US)';
                      update account;
                      System.debug('account' +account);
                  }
              }
              // END: Hardcode of English US

              if (userId != null) { 
                  if (password != null && password.length() > 1) {
                      ApexPages.PageReference lgn = Site.login(email, password, startUrl);
                      aura.redirect(lgn);

                  }
                  else {
                      ApexPages.PageReference confirmRef = new PageReference(regConfirmUrl);
                      aura.redirect(confirmRef);
                  }
              }
              return null;
          }
          catch (Exception ex) {
              Database.rollback(sp);
              SystemLoggerUtil.logError(ex);
              return ex.getMessage();            
          }
     }    

    @AuraEnabled
    public static List<Map<String,Object>> getExtraFields(String extraFieldsFieldSet) { 
        List<Map<String,Object>> extraFields = new List<Map<String,Object>>();
        Schema.FieldSet fieldSet = Schema.SObjectType.User.fieldSets.getMap().get(extraFieldsFieldSet);
        if (fieldSet != null) {
            for (Schema.FieldSetMember f : fieldSet.getFields()) {
                Map<String, Object> fieldDetail = new Map<String, Object>();
                fieldDetail.put('dbRequired', f.getDBRequired());
                fieldDetail.put('fieldPath', f.getFieldPath());
                fieldDetail.put('label', f.getLabel());
                fieldDetail.put('required', f.getRequired());
                fieldDetail.put('type', f.getType());
                fieldDetail.put('value', '');   // client will populate
                extraFields.add(fieldDetail);
            }
        }
        return extraFields;
    } 

}

Best Answer

The problem is not the Portal USER, but the user who CREATES the Portal user.

As test code should be run as specific users (using System.RunAs()), you should create a new user in your test code, assign that user a Role, and then run the createPortalUser method as that user. This will avoid your errors.

And yes, you should also give yourself a role as well. In fact, go ahead and give every internal user a role, just to be complete and to allow control of record visibility using the role hierarchy.

Related Topic