Print this page

Create Portal Roles programmatically using Apex

Knowledge Article Number 000123543
Description Following is a code snippet to create portal roles when there are less than 3 roles for a portal account:

Roles are added Bottom-Up
 
Resolution
Id portalAcctId = '001xxxxxxxxxxxxxx';
Integer roleCnt = [Select count() from UserRole where PortalAccountId = :portalAcctId];

//Execute the create logic if less than 3 roles exist as we can't add 4th role and system will throw an error
if(roleCnt < 3) {
 
	//Add one role, role will be added bottom up
	//If no roles exist, adds User
	//If 1 role (User) exists, adds Manager
	//If 2 roles (Manager, User) exist, adds Executive

	UserRole role = new UserRole();
	role.portalType = 'Partner'; // use 'CustomerPortal' for customer portal roles
	role.PortalAccountId = portalAcctId;
	role.CaseAccessForAccountOwner = 'Edit'; //Modify as needed
	role.OpportunityAccessForAccountOwner = 'Read'; //Modify as needed
	insert role;
}




promote demote