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);

    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;
          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.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)) {

              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;

              // 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);

                  else {
                      ApexPages.PageReference confirmRef = new PageReference(regConfirmUrl);
              return null;
          catch (Exception ex) {
              return ex.getMessage();            

    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
        return extraFields;


3 Answers 3


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.


The Guest user assigned to new accounts created by community self-registration has no role. I solved this problem by adding logic to the Insert Before trigger on the Account object that reassigns accounts owned by this user to a "real" user. You may want to come up with a more elegant method that doesn't embed record Id's, but this should work.

trigger AccountTrigger on Account ( before insert ) {
    if (Trigger.isBefore && Trigger.isInsert) 

public without sharing class AccountTriggerHandler {

    public static void beforeInsert (List<Account> accounts) {
        system.debug('AccountTriggerHandler.beforeInsert accounts: ' + accounts);
        Id guestId = '0056A00000zzzzzzzz'; // the Id of the Guest User in the community
        Id defaultOwnerId = '0056A00000zzzzzzzz'; // the Id of a "real" user
        for (Account account : accounts) {
            if (account.OwnerId == guestId ) {
                account.OwnerId = defaultOwnerId;

You should check that your username has a role assigned to it. Salesforce will not allow a portal contact to be created if the owner/creator doesn't have a role.

You might also check that the portal account's owner has a role assigned to it. See this post for the reason: Any documentation on the CreatePortalUser?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.