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
Ajay DubeyAjay Dubey 

How to enable customer user for existing contact using apex?

For the community self registration page if the user enters the detail, I want to check if the contact already exist on the basis of email entered by user. If it does, I want to create user for that existing contact. How can achieve this?
Best Answer chosen by Ajay Dubey
Anupama SamantroyAnupama Samantroy
Hi Ajay,

Prepare the User record data using the Contact details. Then call the Site.createPortalUser(user, accountId, password, sendEmailConfirmation) method to create the user for you.

Thanks
Anupama

All Answers

Anupama SamantroyAnupama Samantroy
Hi Ajay,

Prepare the User record data using the Contact details. Then call the Site.createPortalUser(user, accountId, password, sendEmailConfirmation) method to create the user for you.

Thanks
Anupama
This was selected as the best answer
Ajay DubeyAjay Dubey
Hi Anupama,
Thanks for the solution, it is working now.I was trying to insert user using insert DML instead of   Site.createPortalUser(user, accountId, password, sendEmailConfirmation). 
Thanks 
Ajay 
Syed Subhan 9Syed Subhan 9
Hi Anupama,
Hi Ajay,

Can anyone please post the code in which you were able to enable or create new users under existing contact in the community. ASAP. It will be very very helpfull. As I don't do that level of SF work yet, so any help would be great.

Waiting for the reply. Thanks in Advance.
Ajay DubeyAjay Dubey
Hi Syed Subhan 9,
I am providing you the complete class, There might be some irrelevent logic in the code for you. 
public class CommunitiesSelfRegistrationController {
    
    public String firstName {get; set;}
    public String lastName {get; set;}
    public String email {get; set;}
    public String password {get; set {password = value == null ? value : value.trim(); } }
    public String confirmPassword {get; set { confirmPassword = value == null ? value : value.trim(); } }
    //public String communityNickname {get; set { communityNickname = value == null ? value : value.trim(); } }
    public string employerCode {get;set;}
    public string SSNLast4 {get;set;}
    public boolean rendered {get;set;} 
    public CommunitiesSelfRegistrationController() {
        rendered = true;
        // Write the code to get employer code from Url as per the instruction from Doc.
        employerCode = apexpages.currentpage().getparameters().get('EmpCode');
        if((employerCode == null) || (employerCode == ' ')){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'We were unable to verify your Registration, please contact your HR department.'));
            rendered = false;
        }
    }
    
    private boolean isValidPassword() {
        return password == confirmPassword;
    }
    
    public PageReference registerUser() {
        
        List<Account> accList = new List<Account>([Select id,name,Employer_Code__c,Community_PreVerification_Required__c from Account where Employer_Code__c =: apexpages.currentpage().getparameters().get('EmpCode') Limit 1]);
        if(!accList.isEmpty()){
            List<Contact> conList = new List<Contact>([Select id,FirstName,LastName,Email,account.Employer_Code__c,SSN_Last_4__c from Contact where SSN_Last_4__c =: SSNLast4 limit 1]);
            if(!conList.isEmpty()){
                String empCode = conList.get(0).account.Employer_Code__c;
                if(empCode == employerCode){
                    String userId = createCommunityUser(conList.get(0).Email,conList.get(0).Email,conList.get(0).FirstName,conList.get(0).LastName,conList.get(0).SSN_Last_4__c);
                    if (userId != null) { 
                        //String startUrl = 'https://comm1-hbgtools1.cs7.force.com/MyHealth';
                        //ApexPages.PageReference lgn = Site.login(email, password, startUrl);
                        PageReference pageRef = new PageReference('/apex/CommunitiesSelfRegConfirm');
                        pageRef.setRedirect(true);
                        return pageRef;
        			}
                }else{
                    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, '"You already have an account to use the Community.  Please click “Already have an account?” on the Signup page to reset your password.'));
                    return null;
                }
            }else{
                if(!accList[0].Community_PreVerification_Required__c){
                    
                    String userId = createCommunityUser(email,email,firstName,lastName,SSNLast4);
                    
                    if (userId != null) { 
                        //String startUrl = 'https://comm1-hbgtools1.cs7.force.com/MyHealth';
                        //ApexPages.PageReference lgn = Site.login(email, password, startUrl);
                        PageReference pageRef = new PageReference('/apex/CommunitiesSelfRegConfirm');
                        pageRef.setRedirect(true);
                        return pageRef;
        			}
                    
                }else{
                    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'We were unable to verify your Registration, please contact your HR department.'));
                }
            }
        }else{
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'We were unable to verify your Registration, please contact your HR department'));
        }
        return null;
    }
    public String createCommunityUser(String username, String email,String firstName,String lastName,String SSNLast4 ){
        
        // it's okay if password is null - we'll send the user a random password in that case
        if (!isValidPassword()) {
            ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR, Label.site.passwords_dont_match);
            ApexPages.addMessage(msg);
            return null;
        }    
        String profileId = null; // To be filled in by customer.
        String roleEnum = null; // To be filled in by customer.
        String accountId = null; // To be filled in by customer.
        //String userName = email;
        String nickname = email.substringBefore('@');
        User u = new User();
        u.Username = username;
        u.Email = email;
        u.FirstName = firstName;
        u.LastName = lastName;
        u.CommunityNickname = nickname;
        //u.ProfileId = profileId;
        u.Contact_SSN_Last_4__c = SSNLast4;
        String userId;
        try {
            userId = Site.createExternalUser(u, accountId, password);
            system.debug('userId::'+userId);
        } catch(Site.ExternalUserCreateException ex) {
            List<String> errors = ex.getDisplayMessages();
            for (String error : errors)  {
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, error));
            }
            System.debug(ex.getMessage());
        }
        return userId;
    }
}