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
Nakul Mudgal 8Nakul Mudgal 8 

Enable customer community user using apex

We have person accounts in our org. to whom we need to give access to our customer community at various stages of an opportunity.

Is there a way we can programmatically enable our person accounts as customer users using apex ?

We have Customer Community Login licenses available in our org
AshlekhAshlekh
Hi,

You can create Potal user by

If you are creating the customer portal user through internally then you can below sample code to create a customer portal user.
--------------------- Customer Portal User created internally----------------- 
Profile pf = [Select id,name from Profile where name ='Volunteer' limit 1];

account acc = [select name from accout where name="individual"];

Contact con = [select id,name,email,lastname,firstname,accoundid from contact where accountid=:accid limit 1];

User u2 = new User(contactId=con.Id, username=con.Email, firstname=con.FirstName,
lastname=con.LastName, email=con.Email,communityNickname = con.LastName + '_' + Rnd,
alias = string.valueof(con.FirstName.substring(0,1) + con.LastName.substring(0,1)), profileid = pf.Id, emailencodingkey='UTF-8',
languagelocalekey='en_US', localesidkey='en_US', timezonesidkey='America/Los_Angeles');
Database.DMLOptions dlo = new Database.DMLOptions();
dlo.EmailHeader.triggerUserEmail= true;
Database.saveresult sr = Database.insert(u2,dlo);
--------------------- Customer Portal User through sites-----------------
Public string Email{get;set;}
Public string FirstName{get;set;}
Public string LastName{get;set;}
Public string CommunityNickname{get;set;}
Public string Passwd{get;set;}
account acc = [select name from accout where name="individual"];
User u = new User();
u.Username = Email;
u.FirstName = FirstName;
u.LastName = LastName;
u.Email = Email;
// u.IsPortalSelfRegistered = true;
u.CommunityNickname = communityNickname;
String pwdd = Passwd;
system.debug('<< before create user >>');
String userId = Site.createPortalUser(u, acc.id, pwdd); // This method create a customer portal user
Or you can also see this link http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_sites.htm


IF it helps you than please mark it as a solution and ENJOY APEX (http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_sites.htm)
shiv@SFDCshiv@SFDC
Hi,

We have to write trigger on opporutnity for your requirments. But i have a quetion here :

There may be multiple contacts associtated with opportunity's account. If opportunity stage is changed do you want to deactivae user access for all the contacts which is related to that account ?
Nakul Mudgal 8Nakul Mudgal 8
Hi Shiv, thank you for responding...

We are not looking to give access to any contacts to our community. We have person accounts attached to our opportunities which need to be enabled as customer users.

And yes we will need the logic to deactivate them as well.

@Ashlekh Gera-
Thanks a lot for the sample code... will this work for Person accounts as well ... i think i'll have to query the personcontactid for the contact.
shiv@SFDCshiv@SFDC
Hi Nakul,

If i am not wrong whenever we creat a customer community user have to create a user(Record of user object). On that user object record we have a lookup of contact , which is going to be a community user. profile for thant user profile will be community portal or community portal +.

The scenario for which i am talking till now is the case when we make a contact as a portal user or customer user.

In this scinario code can be like this (not tested)

trigger deactivateUser on Opportunity (after insert, after update)
{
	Set<Id> accountIdSetToDeactivae = new Set<Id>();
	Set<Id> accountIdSetToActivate = new Set<Id>();
	for(Opportunity op : Trigger.new)
	{
		//collect account Ids for which we want to deactivate user
		if(op.stageName == 'Stage_Name_1_when you want to deactivate User')
		{
			if(op.accountId != NULL)
				accountIdSetToDeactivae.add(op.accountId)
		}
		
		//collect account Ids for which we want to activate user
		if(op.stageName == 'Stage_Name_1_when you want to activate User')
		{
			if(op.accountId != NULL)
				accountIdSetToActivate.add(op.accountId)
		}
	}
	
	//Deactivate user
	if(accountIdSetToDeactivae.size() > 0)
	{
		List<User> userListToDEactivate = new List<User>();
		for(User u : [SELECT Id, Name, IsActive FROM USER WHERE AccountId In: accountIdSetToDeactivae] )
		{
			u.isActive = false;
			userListToDEactivate.add(u);
		}
		
		if(userListToDEactivate > 0)
			update userListToDEactivate;
	}
	
	//activate user
	if(accountIdSetToActivate.size() > 0)
	{
		List<User> userListToActivate = new List<User>();
		for(User u : [SELECT Id, Name, IsActive FROM USER WHERE AccountId In: accountIdSetToActivate] )
		{
			u.isActive = true;
			userListToActivate.add(u);
		}
		
		if(userListToActivate > 0)
			update userListToActivate;
	}
}

NickCANickCA
In my particular use case, I was trying to create a Portal User as soon as they became a client. If you are creating a Person Account and a Portal User, it is simply sufficient to associate the PersonContactId from the Person Account, which is generate automatically once you insert the Person Account record, with the ContactId field on the User, like so:
Account objAccount = [SELECT PersonContactId FROM Account WHERE ... LIMIT 1]; 
// Or if you're creating the Person Account here
// Account objAccount = new Account();
// {Include other parameters here}
// insert Account;

User newUser = new User();
newUser.ContactId = objAccount.PersonContactId; 
// {Include other parameters here}
insert newUser;
Credit: https://salesforce.stackexchange.com/a/46313/51566