+ Start a Discussion
Holly Havelka 10Holly Havelka 10 

Need Help With My Autocomplete Account Field Component/Controller

Hi All,

I have this autocomplete function on the college account field.  See below screenshot.

User-added image

What I want to do is force the user to select one of the accounts listed in the drop-down, if an account name matches what they have typed into the box.  Right now the logic will allow them to create another account in the database, even though it shows one exists in the drop-down, if they just click the 'save' button on the page.  

Here is the controller:
public class ProfileSubmitController {

    public List<SelectOption> genders { get; set; }
    public List<SelectOption> ethnicity { get; set; }
    public List<SelectOption> eligibleToWorkUS { get; set; }
    public List<SelectOption> freeOrReducedLunch { get; set; }
    public List<SelectOption> grantPellRecipient { get; set; }
    public List<SelectOption> parentsHighestEducation { get; set; }
    public List<SelectOption> states { get; set; }
    //public List<SelectOption> collegeList { get; set; }
    public List<SelectOption> primaryPhoneTypes { get; set; }
    public List<SelectOption> primaryAddressTypes { get; set; }
    public List<SelectOption> otherPhoneTypes { get; set; }
    public List<SelectOption> otherAddressTypes { get; set; }
    public List<SelectOption> majorCategory { get; set; }
    public List<SelectOption> secondMajorCategory { get; set; }
    public List<SelectOption> minorCategory { get; set; }

    public ProfileSubmitController() {
        
        eligibleToWorkUS = new List<SelectOption>();
        Schema.DescribeFieldResult fieldResult = Application__c.Eligible_to_work_in_US__c.getDescribe();
        List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry f : ple) {
            eligibleToWorkUS.add(new SelectOption(f.getLabel(), f.getValue()));
        }

        genders = new List<SelectOption>();
        genders.add(new SelectOption('', 'Please Select...'));
        fieldResult = Contact.Gender__c.getDescribe();
        ple = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry f : ple) {
            genders.add(new SelectOption(f.getLabel(), f.getValue()));
        }

        ethnicity = new List<SelectOption>();
        ethnicity.add(new SelectOption('', 'Please Select...'));
        fieldResult = Contact.Ethnicity__c.getDescribe();
        ple = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry f : ple) {
            ethnicity.add(new SelectOption(f.getLabel(), f.getValue()));
        }

        freeOrReducedLunch = new List<SelectOption>();
        fieldResult = Application__c.GAP_Grant_Free_or_Reduced_Lunch__c.getDescribe();
        ple = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry f : ple) {
            freeOrReducedLunch.add(new SelectOption(f.getLabel(), f.getValue()));
        }

        grantPellRecipient = new List<SelectOption>();
        fieldResult = Application__c.Gap_Pell_Grant_Recipient__c.getDescribe();
        ple = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry f : ple) {
            grantPellRecipient.add(new SelectOption(f.getLabel(), f.getValue()));
        }

        parentsHighestEducation = new List<SelectOption>();
        fieldResult = Application__c.Parents_Highest_Level_of_education__c.getDescribe();
        ple = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry f : ple) {
            parentsHighestEducation.add(new SelectOption(f.getLabel(), f.getValue()));
        }

        Map<String, State_List__c> stateList = State_List__c.getAll();
        states = new List<SelectOption>();
        states.add(new SelectOption('', 'Please Select...'));
        List<SelectOption> statesAux = new List<SelectOption>();
        for (String stateName : stateList.keySet()){
            statesAux.add(new SelectOption(stateList.get(stateName).Abbreviation__c, stateName));
        }
        statesAux.sort();
        states.addAll(statesAux);
/*
        collegeList = new List<SelectOption>();
        collegeList.add(new SelectOption('', 'Please Select...'));
        List<Account> sitesList = [SELECT Name FROM Account WHERE RecordType.Name = 'Colleges & Universities'];
        for (Account acc : sitesList){
            if (acc.Name != null){
                collegeList.add(new SelectOption(acc.Id, acc.Name));
            }
        }
*/
        primaryPhoneTypes = new List<SelectOption>();
        primaryPhoneTypes.add(new SelectOption('', 'Please Select...'));
        primaryPhoneTypes.add(new SelectOption('Home', 'Home'));
        primaryPhoneTypes.add(new SelectOption('Cell', 'Cell'));
        primaryPhoneTypes.add(new SelectOption('Office 1', 'Office'));
        primaryPhoneTypes.add(new SelectOption('Other', 'Other'));

        primaryAddressTypes = new List<SelectOption>();
        primaryAddressTypes.add(new SelectOption('', 'Please Select...'));
        fieldResult = Contact.npe01__Primary_Address_Type__c.getDescribe();
        ple = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry f : ple) {
            primaryAddressTypes.add(new SelectOption(f.getLabel(), f.getValue()));
        }

        otherPhoneTypes = new List<SelectOption>();
        otherPhoneTypes.add(new SelectOption('', 'Please Select...'));
        otherPhoneTypes.add(new SelectOption('Home', 'Home'));
        otherPhoneTypes.add(new SelectOption('Cell', 'Cell'));
        otherPhoneTypes.add(new SelectOption('Office', 'Office'));
        otherPhoneTypes.add(new SelectOption('Other', 'Other'));

        otherAddressTypes = new List<SelectOption>();
        otherAddressTypes.add(new SelectOption('', 'Please Select...'));
        fieldResult = Contact.Other_Address_Type__c.getDescribe();
        ple = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry f : ple) {
            otherAddressTypes.add(new SelectOption(f.getLabel(), f.getValue()));
        }

        majorCategory = new List<SelectOption>();
        majorCategory.add(new SelectOption('', 'Please Select...'));
        fieldResult = Contact.College_Major_Category_new__c.getDescribe();
        ple = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry f : ple) {
            majorCategory.add(new SelectOption(f.getLabel(), f.getValue()));
        }

        secondMajorCategory = new List<SelectOption>();
        secondMajorCategory.add(new SelectOption('', 'Please Select...'));
        fieldResult = Contact.College_Major_Category_2nd_Major__c.getDescribe();
        ple = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry f : ple) {
            secondMajorCategory.add(new SelectOption(f.getLabel(), f.getValue()));
        }

        minorCategory = new List<SelectOption>();
        minorCategory.add(new SelectOption('', 'Please Select...'));
        fieldResult = Contact.College_Minor_Category__c.getDescribe();
        ple = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry f : ple) {
            minorCategory.add(new SelectOption(f.getLabel(), f.getValue()));
        }

    }

    @RemoteAction
    public static Boolean savePageOne(String application, String myContact){
        List<Breakthrough_Application_Settings__c> settings = [SELECT Name, 
                                                                    Regular_Deadline__c,
                                                                    Backdoor_Application_Open__c
                                                            FROM Breakthrough_Application_Settings__c 
                                                            WHERE Active__c = true LIMIT 1];
        Datetime backdoorOpen = Datetime.newInstance(settings[0].Backdoor_Application_Open__c, Time.newInstance(0,0,0,0));
        Boolean backdoorApplicationOpen = Datetime.now() >= backdoorOpen;   
        
        Contact cont = (Contact)JSON.deserialize(myContact, Contact.Class);
        Application__c app = (Application__c)JSON.deserialize(application, Application__c.Class);

        if (String.isBlank(cont.College__c) && String.isNotBlank(cont.Other_College__c)){
            RecordType collegeRecordType = [SELECT Id FROM RecordType WHERE Name = 'Colleges & Universities'];
            Account newCollege = new Account(RecordTypeId = collegeRecordType.Id, Name = cont.Other_College__c);
            insert newCollege;
            cont.College__c = newCollege.Id;
        }

        cont.Other_College__c = '';

        update cont;
        app.Page_1_Status__c = 'Complete';

        if (backdoorApplicationOpen) {
            RecordType recordType = [select Name from RecordType where Name = 'Backdoor' and SObjectType = 'Application__c'];
            app.RecordTypeId = recordType.Id;
            app.X2nd_City_Preference__c = null;
            app.X2nd_City_Housing_Needed__c = null;
            app.X3rd_City_Preference__c = null;
            app.X3rd_City_Housing_Needed__c = null;
        }
        
        try {
            update app;
        } catch (Exception e) {
            app.Page_1_Status__c = 'In Progress';
            update app;
        }
        Datetime regularDeadline = Datetime.newInstance(settings[0].Regular_Deadline__c, Time.newInstance(0,0,0,0)).addDays(1);
        return ((Datetime.now() >= regularDeadline) && !backdoorApplicationOpen);
        
    }

    @RemoteAction
    public static List<Result> getSearchResults(String searchTerm) {
        List<Result> resultsList = new List<Result>();
        
        searchTerm = searchTerm + '*';
        
        List<List<sObject>> searchResults = [FIND :searchTerm IN ALL FIELDS RETURNING Account(Id, Name, BillingCity, BillingState WHERE RecordType.Name = 'Colleges & Universities')];

        if(!searchResults.isEmpty()) {
            for(List<sObject> objects : searchResults) {
                for(sObject obj : objects) {
                    Account a = (Account)obj;
                    Result r = new Result(a.Name, a.Id, a.BillingCity, a.BillingState);
                    resultsList.add(r);
                }
            }
        }
        
        return resultsList;
    }
    
    public class Result {
        public String name {get; set;}
        public String recordId {get; set;}
        public String BillingCity {get; set;}
        public String BillingState {get; set;}    
        public Result(String name, String recordId, String BillingCity, String BillingState) {
            this.name = name;
            this.recordId = recordId;
            this.BillingCity = BillingCity;
            this.BillingState = BillingState;
        }
    }

}



Here is the section of the component that does the remotesearch for the account names:
function doRemoteSearch() {
            var searchTerm = document.getElementsByClassName('searchBox')[0].value;
            
            if(searchTerm.length >= 2) {
                Visualforce.remoting.Manager.invokeAction(
                    '{!$RemoteAction.ProfileSubmitController.getSearchResults}',
                    searchTerm,
                    function(result, event) {
                        if(event.status) {

                            var tbody = document.getElementById('resultsTableBody');
                            var tbodyRows = document.getElementById('resultsTableBody').rows.length;

                            tbody.innerHTML = '';

                            var resultLength = result.length;
                            if (resultLength != 0){
                                document.getElementsByClassName('resultsTable')[0].style.display = '';
                                
                                for(var i = 0; i < resultLength; i++) {
                                        
                                        var wrapperTbody = document.createElement('tbody');
                                        //add id and name to data attributes of the tbody element
                                        wrapperTbody.dataset.id = result[i].recordId;
                                        wrapperTbody.dataset.name = result[i].name;
                                        wrapperTbody.addEventListener("click", fillWithSelectedCollege);
                                        
                                        var tr = document.createElement('tr');
                                        var td = tr.appendChild(document.createElement('td'));
                                        
                                        //add name
                                        tr = document.createElement('tr');
                                        td = tr.appendChild(document.createElement('td'));
                                        td.innerHTML = result[i].name;
                                        
                                        wrapperTbody.appendChild(tr);
                                        //add city and state
                                        tr = document.createElement('tr');
                                        td = tr.appendChild(document.createElement('td'));
                                        td.innerHTML = '<span style="font-size:0.8em;font-style:italic">'
                                        + result[i].BillingCity + ',' + result[i].BillingState +
                                        '</span>';

                                        wrapperTbody.appendChild(tr);

                                        tbody.appendChild(wrapperTbody);


                                }
                            } else {
                                document.getElementsByClassName('resultsTable')[0].style.display = 'none';
                            }
                        } else {
                            alert('An error occurred');
                        }
                    },
                    {escape: true}
                );
            } else {
                document.getElementsByClassName('resultsTable')[0].style.display = 'none';
            }
        }

<!-- ************************************ UNDERGRADUATE COLLEGE SUBSECTION ************************************ -->
			<apex:outputPanel styleClass="undergraduate" style="display: none">
				<apex:pageBlockSection id="sndsubSection" columns="1" collapsible="false">
					<apex:facet name="header">
						<apex:outputText styleClass="subSectionHeader" value="Undergraduate College"/>
					</apex:facet>

					<apex:panelGrid columns="1">
						<apex:outputLabel styleClass="customLabel">Undergraduate College <span class="reqMark">*</span></apex:outputLabel>
						<apex:inputText value="{!actualContact.Other_College__c}" maxlength="255" size="80" label="" onkeyup="doRemoteSearch()" styleClass="searchBox" id="otherCollege"/>
						<apex:inputText value="{!actualContact.College__c}" styleClass="accId" style="display: none" id="college"/>
					</apex:panelGrid>      
					<table class="resultsTable" style="display: none">
						<tbody id="resultsTableBody">
						</tbody>
					</table>

					<apex:panelGrid columns="2">
						<apex:panelGrid columns="1">
							<apex:outputLabel styleClass="customLabel">Graduation Year <span class="reqMark">*</span></apex:outputLabel>
							<apex:inputText value="{!actualContact.College_Grad_Year__c}" size="20" label="" maxlength="4" styleClass="numberInput" id="collegeGradYear" onchange="checkMinLength(this, 4)"/>
						</apex:panelGrid>

						<apex:panelGrid columns="1">
							<apex:outputLabel styleClass="customLabel">Cumulative Undergraduate GPA <span class="reqMark">*</span></apex:outputLabel>
							<apex:inputText value="{!actualContact.College_GPA__c}" size="5" label="" maxlength="3" html-pattern="\d{1}\.\d{1}" onchange="checkCollegeGPA(this)" id="collegeGPA"/>
							<apex:outputLabel style="color: red; font-weight: bold; display: none;" id="collegeGPAErrorLabel"/>
						</apex:panelGrid>
					</apex:panelGrid>
Any thoughts on how to add this requirement into the functionality?