[SalesForce] Getting Issues while creating User

I am trying to create an User but I am getting error as follows:

18:46:26:307 FATAL_ERROR System.DmlException: Insert failed.
First exception on row 0; first error: UNKNOWN_EXCEPTION,
portal account owner must have a role: []

And when I try to fix above issue by providing a UserRoleId for the user which I want to create then getting issue as follows:

FATAL_ERROR System.DmlException: Insert failed. First exception on row 0;
first error: FIELD_INTEGRITY_EXCEPTION, High Volume Portal Users cannot have a user role: Role ID: [UserRoleId]

In above cases the profile's userType is 'CspLitePortal'

And further, when I change the profile's userType to 'Standard' and try to create an User, the error I got is as follows:

18:41:40:576 FATAL_ERROR System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, only portal users can be associated to a contact: []

For my use case, I need to have contact Object associated with the User. Since Contact can have an attachement. My use case facilitates a photo upload for every user created. At the time of upload, I am storing the image base64 data as an attachment to that User's Contact record (which acts as Parent-Id for the attachment). We can't have an Attachment with User's record Id as parent-Id.
Any workaround.

Best Answer

You need to be creating the User using a User who has a Salesforce User license, not a Community or Portal User license. That Salesforce User should have a Role and would be the Account owner for the Contact you're creating for use in your Portal. Steps would be as follows:

If this is a TestClass, use RunAs. If it is production, a Portal User cannot create Users unless you have your code run in System Mode with an API User with a Role.

  1. Create Account
  2. Insert Account
  3. Create Contact with AccountID from above
  4. Insert Contact
  5. Create User with ContactId from above
  6. Insert User