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
Kristen Aldrich 14Kristen Aldrich 14 

Communities self-register error "accountId parameter not valid" related to Apex Class

I've been receiving email notifications with Subject: Registration error in site AMC_Community with the body: "AMC_Community registration accountID parameter value is not valid". This issue seems to happen when someone tries to self register for our Community for the first time. If they have a preexisting contact in SF, they are able to register a user in the Community. Otherwise, this error is thrown. After speaking with SF support, we narrowed down the issue to the Apex Class 'CommunitiesSelfRegController'
/**
* An apex page controller that supports self registration of users in communities that allow self registration
*/
public class CommunitiesSelfRegController {
    
    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 Zipcode{get;set;}
    public String City{get;set;}
    public String Street{get;set;}
    String userId;
    String userName ;
    List<Contact> ConList = new list<contact>();
    Map<id,user> MapOfUser =  new Map<id,user>();
    user u;
    user[] UsrOld;
    boolean CheckCon = false;
    DateTime currentTime = System.now(); 
    Long timeInMili = currentTime.getTime()/1000; 
    map<id,contact> MapofExternalContact = new map<id,contact>();
    Map<id,id> MapofUserContact = new map<id,id>();
    set<id> SetOfContacts = new set<id>();
    boolean createaccount=true;

    
    //Aman
    public String country {get;set;}
    public String state {get;set;}
    //Aman
    public CommunitiesSelfRegController() {getCountries();getStates();}
    
    private boolean isValidPassword() {
        return password == confirmPassword;
    }
    
    public List<SelectOption> getCountries()
    {
        List<SelectOption> options = new List<SelectOption>();
        options.add(new SelectOption('None','--- Select ---'));        
        options.add(new SelectOption('United States','United States'));
        options.add(new SelectOption('Canada','Canada'));
        return options;
    } 
    
    public List<SelectOption> getStates()
    {
        List<SelectOption> options = new List<SelectOption>();
        
        if(country == 'United States')
        {   
            options.add(new SelectOption('None','--- Select ---'));    
            List<countrystates__c>  CountryList= [select country__c,state__c,abbrevation__c from countrystates__c where country__c ='United States' order by state__c];
            For(Countrystates__c CS : CountryList){
                options.add(new SelectOption(Cs.abbrevation__c ,CS.State__c));  
                
            }
            
        }
        else if(country == 'Canada')
        {   
            options.add(new SelectOption('None','--- Select ---'));    
            List<countrystates__c>  CountryList= [select country__c,state__c,abbrevation__c from countrystates__c where country__c ='Canada'];
            For(Countrystates__c CS : CountryList){
                options.add(new SelectOption(Cs.abbrevation__c ,CS.State__c));  
                
            }
            
        }
        else
        {
            options.add(new SelectOption('None','--- Select ---'));
        }      
        return options;
    }       
    
    public PageReference registerUser() {
        
        // 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;
        }    
        
        
        try {
            
            for(contact con : [select id,name,firstname,lastname,mailingpostalcode,email,accountid from contact where email = :email]){
                
                MapofExternalContact.put(con.id,con);
                SetOfContacts.add(con.id);
                 
                
                
            }
            
            for(user u : [select id,contactid from user where contactid in : SetOfContacts]){
                if(u.id != null){
                MapofUserContact.put(u.contactid,u.id);
                }
            }
            if(MapofExternalContact.isempty()==false){
                for(contact c :MapofExternalContact.values()){
                    if(c.email == email && MapofUserContact.containskey(c.id)){
                        
                        ApexPages.Message msg1 = new ApexPages.Message(ApexPages.Severity.ERROR, 'User already exists in database');
                        ApexPages.addMessage(msg1);
                        return null;  
                        
                    }else if (!MapofUserContact.containskey(c.id) && c.firstname.equals(firstname) && c.lastname == lastname && c.mailingpostalcode == Zipcode && c.email == email){
                        
                        u = CreateCommUser.CreateUser(label.ProfileID,firstName,LastName,email, c.id);   
                        userId = (String)u.id;
                        
                        checkcon=true;
                    }else if (!MapofUserContact.containskey(c.id) && c.email == email ) {
                        
                        String profileId = label.ProfileID;// To be filled in by customer.
                        String roleEnum = '';// To be filled in by customer.                
                        String accountId = c.accountid; // To be filled in by customer.                
                        userName = email;
                        List<string> split = Email.split('@', 0);
                        User u = new User();
                        u.Username = userName;
                        u.Email = email;
                        u.FirstName = firstName;
                        u.LastName = lastName;
                        u.CommunityNickname = split[0]+timeInMili;
                        u.ProfileId = label.ProfileID; 
                        If(!String.isBlank(Zipcode) || zipcode<>null){
                            u.PostalCode=zipcode;    
                        }
                        If((!String.isBlank(Country) || country<>null) && (Country=='Canada'||country=='United States')){
                            u.country=country;
                        }
                        If(!String.isBlank(city) || city<>null){
                            u.city=city;
                        }
                        If((!String.isBlank(State) || state<>null) && state!= 'None'){
                            u.state=state;}
                        If(!String.isBlank(street) || street<>null){
                            u.street=street;}
                        u.EmailEncodingKey = 'UTF-8';
                        u.LanguageLocaleKey = 'en_US';
                        u.LocalesIdKey = 'en_US';
                        u.TimezonesIdKey = 'America/New_York';                
                        userId = Site.createExternalUser(u, accountId, password);   
                        createaccount=false; 
                    }
                    
                }
            }       else if(MapofExternalContact.isempty()==true){
                
                String profileId = label.ProfileID;// To be filled in by customer.
                String roleEnum = '';// To be filled in by customer.                
                String accountId = Label.CommunityHouseHoldAccount; // To be filled in by customer.                
                userName = email;
                List<string> split = Email.split('@', 0);
                User u = new User();
                u.Username = userName;
                u.Email = email;
                u.FirstName = firstName;
                u.LastName = lastName;
                u.CommunityNickname = split[0]+timeInMili;
                u.ProfileId = label.ProfileID; 
                If(!String.isBlank(Zipcode) || zipcode<>null){
                    u.PostalCode=zipcode;    
                }
                If((!String.isBlank(Country) || country<>null) && (Country=='Canada'||country=='United States')){
                    u.country=country;
                }
                If(!String.isBlank(city) || city<>null){
                    u.city=city;
                }
                If((!String.isBlank(State) || state<>null) && state!= 'None'){
                    u.state=state;}
                If(!String.isBlank(street) || street<>null){
                    u.street=street;}
                u.EmailEncodingKey = 'UTF-8';
                u.LanguageLocaleKey = 'en_US';
                u.LocalesIdKey = 'en_US';
                u.TimezonesIdKey = 'America/New_York';                
                userId = Site.createExternalUser(u, accountId, password);                
            }
            
        }catch(exception ex) {
            
            string errors = ex.getMessage();      
            integer linenumber = ex.getLineNumber();                  
            ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR, errors);
            ApexPages.addMessage(msg);
        } 
        
        if (userId != null) { 
            if (password != null && password.length() > 1) {
                //return Site.login(userName, password, ApexPages.currentPage().getParameters().get('startURL'));
            }
            else {
                
                PageReference page = System.Page.CommunitiesSelfRegConfirm;
                page.setRedirect(true);
                if(Checkcon == false){
                    CreateCommUser.CreateUpdateAccount(userid,createaccount);
                }
                return page;                
                
            }
        }
        return null;
        
        
    }
}

but I'm at a loss as to what is wrong with the code, which was developed and implemented by a consultant we no longer work with. I'll paste the code here. Any help is greatly appreciated!