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
mlindsaymlindsay 

Controller to auto match self register users to contacts in SF Community

All,

We have deployed the SF community, but when people use the self register link on the site SF creates a contact record and user record on a default account even if the email address matches a current customer.  As you can image managing the default account of contacts is not something I want to deal with.

So I am looking for a way to auto match users to their contacts to their user records if the email addresses match.  I understand that this can done with a controller.  I don't do that level of SF work yet, so any help would be great.

Thanks,

Michael
Ashish_SFDCAshish_SFDC
Hi , 


Read through the discussion below, 

Enable portal user for existing contacts during sites self-registration

https://developer.salesforce.com/forums/ForumsMain?id=906F000000099gQIAQ


Regards,
Ashish
Gigi.OchoaGigi.Ochoa
There should be an existing Registration Page and custom controller that you can modify.  You would query for your contact and associate that Contact to the User you are creating.  

....
....
....     
        List<Contact> existingContact = [SELECT Id, AccountId FROM Contact WHERE Email = :email];
        if(existingContact.size() > 0)
        {
        	contactId = existingContact[0].Id;
        	accountId = existingContact[0].AccountId;
        }
        else
        {
                accountId = your default accountid;
        }
       

        User u = new User();
        u.Username = userName;
        u.Email = email;
        u.FirstName = firstName;
        u.LastName = lastName;
        u.CommunityNickname = userName;  
        if(contactId != null) u.ContactId = contactId;
        u.ProfileId = profileId;
        
        String userId = Site.createPortalUser(u, accountId, password);
....
....

Sharing will be an issue unless you make the controller without sharing - not recommended.  You could create another class that is without sharing to get existing contactId and accountId info.

chris.noechris.noe
What happens if the contact you find is associated to an account that is not "Enabled As Partner"?  You can't set up contacts as community users via the standard UI without first enabling the Account as a partner.  Can this all be done via Apex?