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
ABHISHEK SINGH 237ABHISHEK SINGH 237 

When email is entered on registration page and that email exist on contact email address,the existing contact should be enabled as a User.Please help.

Hello Team,
 I have a Vf page for User Registration purpose Consisting of three fields First Name,Last Name,Email on clicking of proceed button i am performing below operations:-
1) if user exist by the entered email and is active have to peroform something.(Done)
2) if user don't exist by the entered email than have to create new user .(Done)
3) if by entered email any contact exist in than that contact has to be enabled as a user.(Not Working)
I am pasting both my vf page and apex controller.

<VisualForce Page>
<apex:page docType="html-5.0"
           showHeader="false"
           standardStylesheets="false"
           applyBodyTag="false"
           applyHtmlTag="false"
           controller="DBA_RegistrationClass">
    
    <apex:composition template="CPBase__template">
        
        <apex:define name="pageTitle">
            User Registration
        </apex:define>
        <apex:define name="pageStyles">
            <style>
                .btn_algn_rt{
                float: right;
                margin-right: 96px;
                margin-top: 21px;
                }
                .form-control{
                width: 93% !important;
                }
                .section-heading {    
                padding-left: 0 !important;
                }
                .row_cstm {
                margin-top: 12px;
                }                            
            </style>
        </apex:define>   
        <apex:define name="supernavRight">
            
        </apex:define>
        <apex:define name="pageMain">
            <div class="container noprint">
                <div class="well">
                    <apex:outputPanel id="msg">
                        <div class="well text-center">
                            <p class="errorMessage"></p>
                            <Framework:messages />
                        </div> 
                    </apex:outputPanel>
                    <apex:form html-novalidate="true" id="searchForm">
                        <apex:outputPanel id="thePanel">  
                            <script> var sbutton = document.getElementById("{!$Component.processBtn}"); </script>
                            <script>
                                function does_Userexist(){
                                console.log('user == ' + {!isUserExist});
                                if({!isUserExist}){
                                    alert('User Exists! Please login to continue');
                                    location.href ="CPBase__custom_login";
                                }
                                else{
                                    alert('Thank You. Please check your email to verify your account.')
                                }
                            }
                            function noenter(ev){ 
                                var key = ev.charCode ? ev.charCode : ev.keyCode ? ev.keyCode : 0;
                                console.log(key);
                                
                                if (window.event && window.event.keyCode == 13 || ev.which == 13) {
                                    
                                    //alert('here');
                                    //Proceedaction();
                                    $("[id$=searchButton]").click();
                                    //$('#searchForm').submit();
                                    ev.preventDefault();
                                    return false;
                                } else {
                                    return true;
                                }
                            }
                            </script>
                        </apex:outputPanel>  
                        <div class="form-horizontal" role="form">
                            <div class="container m-t-30">
                                <!-- <h3 class="section-heading"> Section heading</h3> -->
                                <!-- Page begins -->
                                <div class="row row_cstm">
                                    <div class="col-sm-12">
                                        <apex:outputLabel value="{!$Label.Sample}" />
                                    </div>    
                                </div>
                                <div class="row row_cstm">
                                    <div class="col-sm-12">
                                        <apex:commandLink action="{!redirect}" value="Sign in here"/> to access the DBA Community.
                                    </div>
                                </div>
                                <apex:repeat value="{!Fields}" var="f"> 
                                    <div class="row row_cstm">
                                        <div class="col-sm-12">
                                            <label>{!$ObjectType.User.fields[f].Label}</label> 
                                            <apex:inputField value="{!usernew[f.fieldPath]}" styleClass="form-control" required="{!OR(f.required, f.dbrequired)}" onkeypress="return noenter(event);"/>
                                        </div>
                                    </div>
                                </apex:repeat>
                                <div class="row btn_algn_rt row_cstm">
                                    <div class="col-sm-6">
                                        <apex:commandButton value="Cancel" action="{!cancelaction}" styleclass="btn btn-info fonteva-slds-button slds-button slds-button--neutral FrameworkButton"/> 
                                    </div>
                                    <div class="col-sm-6">
                                        <apex:commandButton value="Proceed" id="searchButton" action="{!Proceedaction}" oncomplete="does_Userexist();" styleclass="btn btn-info btn-wide" reRender="thePanel,msg" />  
                                    </div>
                                </div>
                                <!-- Page Ends -->
                            </div> 
                        </div>  
                    </apex:form>
                </div>
            </div>  
        </apex:define>
        <apex:define name="pageScripts">
            
            <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
            <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
            
            <script type="text/javascript">
            var js$ = jQuery.noConflict();   
            
            </script>
        </apex:define>
        
    </apex:composition>
    
</apex:page>

<-----apex controller---------->

global class DBA_RegistrationClass {
    public Boolean isUserExist{get;set;}
    global User usernew{get;set;}
    
    public DBA_RegistrationClass(){
        isUserExist=false;
        usernew = new User();
    }
    // fieldset for user
    public List<Schema.FieldSetMember> getFields() {
        return SObjectType.User.FieldSets.Registration_Page_Field_Set.getFields();
    }
    
    public PageReference redirect(){
        PageReference pageRef = new PageReference('/apex/DBA_Login');
        pageRef.setRedirect(true);
        return pageRef;
    }
    
    public PageReference proceedaction(){
        
        if(user.Email==NULL){
            Framework.Message.addMessage('Please Enter Email', Framework.Message.Severity.Warning);
            //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING,'Please select atleast one contact'));
            return null;
        }
        Profile  p = [select id,Name from Profile where name ='Customer Community Login User' LIMIT 1];
        UserRole ur =[Select id,name from UserRole where Name='CEO'];
        List<Contact> contactList =[SELECT ID,name,Email FROM Contact WHERE Email=:usernew.Email];
        List<User> userListToInsert = new List<User>();
        if(contactList.size()>0){
                User newUserTOInsert = new User();
                newUserTOInsert.Username = contactList.get(0).Email;
                newUserTOInsert.CommunityNickname = contactList.get(0).Email;
                newUserTOInsert.ContactId = contactList.get(0).Id;     
                newUserTOInsert.Email = contactList.get(0).Email;
                newUserTOInsert.EmailEncodingKey = 'ISO-8859-1';
                newUserTOInsert.FirstName = contactList.get(0).FirstName;
                newUserTOInsert.LastName = contactList.get(0).LastName;
                newUserTOInsert.IsActive = true;
                newUserTOInsert.ProfileId = p.Id;
                newUserTOInsert.UserRoleId = ur.Id;
                userListToInsert.add(newUserTOInsert);
        }
        insert userListToInsert;
        
        List<user> activecommunityuser=[SELECT ID,name,Email FROM User WHERE IsActive=True AND Email=:usernew.Email and ContactId!=null];
        if(activecommunityuser.size()>0){
            isUserExist= TRUE;
        }
        else{      
            Profile  p1 = [SELECT id,Name FROM Profile WHERE name ='Customer Community Login User' LIMIT 1];
            UserRole urerObj =[SELECT id,name FROM UserRole WHERE Name='CEO'];
            
            try{
                Account acc = [Select Id From Account where Name='Design Students' LIMIT 1];
                usernew.userName=usernew.Email;
                usernew.CommunityNickname=usernew.Email;
                Site.createExternalUser(usernew, String.valueOf(acc.Id)); 
            }
            catch(exception ex){
                Framework.Message.addMessage(ex.getmessage(), Framework.Message.Severity.Warning);
                //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING,'Please select atleast one contact'));
            }      
        }          
          PageReference page = new PageReference('https://www.dba.org.uk');
          page.setRedirect(true);    
          return page;
    }
    
    public PageReference cancelaction(){
        PageReference pageRef = new PageReference('https://www.dba.org.uk');
        pageRef.setRedirect(true);
        return pageRef;
    }
    
}

Please provide your valuable inputs.
Many thanks in advance.