+ Start a Discussion
Holly Havelka 10Holly Havelka 10 

Dynamic Search For Account Name Field

Hi all,

I have this controller and component which allows for a dynamic search to help candidates select the name of the right college account.  I want to display other criteria for the end-user in the 'results table' so that they can choose the right account, especially if there are duplicate account names that appear in the search results table.  For example, I would like to add the ability of city, state to be displayed when they search for the account name.

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 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);
                    resultsList.add(r);
                }
            }
        }
        
        return resultsList;
    }
    
    public class Result {
        public String name {get; set;}
        public String recordId {get; set;}       
        public Result(String name, String recordId) {
            this.name = name;
            this.recordId = recordId;
        }
    }

}
Best Answer chosen by Holly Havelka 10
Alain CabonAlain Cabon
Hi Holly,

A first change could be:
 
public class ProfileSubmitController {
...
      @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;                       
        }
    }
}

BillingCity,BillingState and/or City__c, State__c / ShippingCity,ShippingState and so on (according your

Your code is quite big and complicated so the complete validation is not easy. 

Regards

All Answers

Holly Havelka 10Holly Havelka 10
Here is the controller:
Here is the component (modified due to size restrictions):
<apex:component controller="ProfileSubmitController" allowDML="true">

	<apex:attribute name="actualContact" type="Contact" description="The contact to be updated"/>
	<apex:attribute name="actualApplication" type="Application__c" description="The application to be updated"/>
	
	<script>
		function startupSchoolInfoSection(){
			if ("{!actualContact.High_School_Name__c}" != '' || "{!actualContact.High_School_Grad_Year__c}" != ''){
				$('select[id="highSchoolOrCollege"]')[0].value = 'highSchool';
				manageSchoolInfoSection($('select[id="highSchoolOrCollege"]')[0]);
			} else if("{!actualContact.Other_College__c}" != '' || "{!actualContact.College__c}" != '' || "{!actualContact.College_Grad_Year__c}" != '' || "{!actualContact.College_Major_Category_new__c}" != '' || "{!actualContact.College_Major_Category_2nd_Major__c}" != '' || "{!actualContact.College_Minor_Category__c}" != ''  || "{!actualContact.College_Major_s__c}" != ''){
				$('select[id="highSchoolOrCollege"]')[0].value = 'undergraduate';
				manageSchoolInfoSection($('select[id="highSchoolOrCollege"]')[0]);
			}
		}
		$(function(){startupSchoolInfoSection();});
		function manageSchoolInfoSection(selector) {
			if (selector.value == 'none'){
				document.getElementsByClassName('highSchool')[0].style.display = 'none';
				document.getElementsByClassName('undergraduate')[0].style.display = 'none';
			} else if (selector.value == 'highSchool') {
				document.getElementsByClassName('highSchool')[0].style.display = '';
				document.getElementsByClassName('undergraduate')[0].style.display = 'none';
			} else if (selector.value == 'undergraduate') {
				document.getElementsByClassName('undergraduate')[0].style.display = '';
				document.getElementsByClassName('highSchool')[0].style.display = 'none';
			}
		}
		function doRemoteSearch() {
			var searchTerm = document.getElementsByClassName('searchBox')[0].value;
			
			if(searchTerm.length >= 2) {
				Visualforce.remoting.Manager.invokeAction(
					'{!$RemoteAction.ProfileSubmitController.getSearchResults}',
					searchTerm,
					function(result, event) {
						console.log(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 tr = document.createElement('tr');
										var td = tr.appendChild(document.createElement('td'));
										td.innerHTML = result[i].name;
										td.addEventListener("click", fillWithSelectedCollege);
										var td2 = tr.appendChild(document.createElement('td'));
										td2.innerHTML = result[i].recordId;
										td2.style.display = 'none';
										
										tbody.appendChild(tr);
								}
							} else {
								document.getElementsByClassName('resultsTable')[0].style.display = 'none';
							}
						} else {
							alert('An error occurred');
						}
					},
					{escape: true}
				);
			} else {
				document.getElementsByClassName('resultsTable')[0].style.display = 'none';
			}
		}
		function fillWithSelectedCollege(element) {
			document.getElementsByClassName('searchBox')[0].value = element.target.textContent;
			document.getElementsByClassName('accId')[0].value = element.target.nextSibling.textContent;
			document.getElementsByClassName('resultsTable')[0].style.display = 'none';
		}

		function savePageOne(){
			if($("label[id$='highSchoolGPAErrorLabel']")[0].style.display == 'none' && $("label[id$='collegeGPAErrorLabel']")[0].style.display == 'none'){
				showSpinner();
				var contact = '{"Nickname__c":"'+$('input[id$="nickname"]')[0].value+'",'+
							'"Gender__c":"'+$('select[id$="gender"]')[0].value+'",'+
							'"Please_specify_Sex__c":"'+$('input[id$="specifySex"]')[0].value+'",'+
							'"Ethnicity__c":"'+$('select[id$="ethnicity"]')[0].value+'",'+
							'"Ethnicity_Description__c":"'+$('input[id$="ethnicityDescription"]')[0].value+'",'+
							'"Phone":"'+$('input[id$="phone"]')[0].value+'",'+
							'"Primary_Phone_Type__c":"'+$('select[id$="phoneType"]')[0].value+'",'+
							'"MailingStreet":"'+$('input[id$="street"]')[0].value+'",'+
							'"MailingCity":"'+$('input[id$="city"]')[0].value+'",'+
							'"npe01__Primary_Address_Type__c":"'+$('select[id$="addressType"]')[0].value+'",'+
							'"MailingPostalCode":"'+$('input[id$="postalCode"]')[0].value+'",'+
							'"MailingState":"'+$('select[id$="state"]')[0].value+'",'+
							'"OtherPhone":"'+$('input[id$="otherPhone"]')[0].value+'",'+
							'"Other_Phone_Type__c":"'+$('select[id$="otherPhoneType"]')[0].value+'",'+
							'"OtherStreet":"'+$('input[id$="otherStreet"]')[0].value+'",'+
							'"OtherCity":"'+$('input[id$="otherCity"]')[0].value+'",'+
							'"Other_Address_Type__c":"'+$('select[id$="otherAddressType"]')[0].value+'",'+
							'"OtherPostalCode":"'+$('input[id$="otherPostalCode"]')[0].value+'",'+
							'"OtherState":"'+$('select[id$="otherState"]')[0].value+'",'+
							'"Home_State__c":"'+$('select[id$="homeState"]')[0].value+'",'+
							'"Home_City__c":"'+$('input[id$="homeCity"]')[0].value+'",'+
							'"Secondary_Email__c":"'+$('input[id$="secondaryEmail"]')[0].value+'",';
				if($('input[id$="birthdate"]')[0].value != ''){
					var birthDate = new Date($('input[id$="birthdate"]')[0].value);
					birthDate = birthDate.toISOString().substring(0,10);
					contact += '"Birthdate":"'+birthDate+'",';
				}
				if ($('select[id="highSchoolOrCollege"]')[0].value == 'highSchool'){
					contact += '"Other_College__c":"",'+
								'"College__c":"",'+
								'"College_Grad_Year__c":"",'+
								'"College_Major_Category_new__c":"",'+
								'"College_Major_Category_2nd_Major__c":"",'+
								'"College_Minor_Category__c":"",'+
								'"College_Major_s__c":"",'+
								'"High_School_Name__c":"'+$('input[id$="highSchoolName"]')[0].value+'",'+
								'"High_School_Grad_Year__c":"'+$('input[id$="highSchoolGradYear"]')[0].value+'",';
					if ($('input[id$="collegeGPA"]')[0].value != ''){
						contact += '"College_GPA__c":"",';
					}
					if ($('input[id$="highSchoolGPA"]')[0].value != ''){
						contact += '"High_School_GPA__c":"'+$('input[id$="highSchoolGPA"]')[0].value+'",';
					}
				}
				if ($('select[id="highSchoolOrCollege"]')[0].value == 'undergraduate'){
					contact += '"High_School_Name__c":"",'+
								'"High_School_Grad_Year__c":"",';
					if ($('input[id$="highSchoolGPA"]')[0].value != ''){
						contact += '"High_School_GPA__c":"",';
					}
					if ($('input[id$="college"]')[0].value != ''){
						contact += '"Other_College__c":"",'+
									'"College__c":"'+$('input[id$="college"]')[0].value+'",';
					} else {
						if ($('input[id$="otherCollege"]')[0].value != ''){
							contact += '"Other_College__c":"'+$('input[id$="otherCollege"]')[0].value+'",'+
										'"College__c":"",';
						} else {
							contact += '"Other_College__c":"",'+
										'"College__c":"",';
						}
					}
					contact += '"College_Grad_Year__c":"'+$('input[id$="collegeGradYear"]')[0].value+'",'+
								'"College_Major_Category_new__c":"'+$('select[id$="collegeMajorCategory"]')[0].value+'",'+
								'"College_Major_Category_2nd_Major__c":"'+$('select[id$="collegeSecondMajorCategory"]')[0].value+'",'+
								'"College_Minor_Category__c":"'+$('select[id$="collegeMinorCategory"]')[0].value+'",'+
								'"College_Major_s__c":"'+$('input[id$="collegeMajorMinor"]')[0].value+'",';
					if ($('input[id$="collegeGPA"]')[0].value != ''){
						contact += '"College_GPA__c":"'+$('input[id$="collegeGPA"]')[0].value+'",';
					}
				}

				contact += '"Id":"'+"{!actualContact.Id}"+'"}';

				var grantFree = '';
				var grantPell = '';
				var grantParents = '';
				var grantParentsHighest = '';
				var highSchoolOrCollege = document.getElementById('highSchoolOrCollege').value;
				if (highSchoolOrCollege == 'highSchool'){
					var grantFreeVals = $('table[id$="grantFreeSchool"] input:checked');
					for (var i = 0; i < grantFreeVals.length; i++) {
						grantFree += ';'+grantFreeVals[i].value;
					};
					grantFree = grantFree.substring(1,grantFree.length);
					var grantParentsHighestVals = $('table[id$="grantParentsHighestSchool"] input:checked');
					for (var i = 0; i < grantParentsHighestVals.length; i++) {
						grantParentsHighest += grantParentsHighestVals[i].value;
					};
					grantParents = grantParents.substring(1,grantParents.length);
				} else if (highSchoolOrCollege == 'undergraduate'){
					var grantPellVals = $('table[id$="grantPellCollege"] input:checked');
					for (var i = 0; i < grantPellVals.length; i++) {
						grantPell += ';'+grantPellVals[i].value;
					};
					grantPell = grantPell.substring(1,grantPell.length);
					var grantParentsHighestVals = $('table[id$="grantParentsHighestCollege"] input:checked');
					for (var i = 0; i < grantParentsHighestVals.length; i++) {
						grantParentsHighest += grantParentsHighestVals[i].value;
					};
					grantParents = grantParents.substring(1,grantParents.length);
				}

				var eligibleToWorkUS = '';
				var eligibleToWorkUSVals = $('table[id$="eligibleToWorkUS"] input:checked');
				for (var i = 0; i < eligibleToWorkUSVals.length; i++) {
					eligibleToWorkUS += ';'+eligibleToWorkUSVals[i].value;
				};
				eligibleToWorkUS = eligibleToWorkUS.substring(1,eligibleToWorkUS.length);

				var app = '{"Eligible_to_work_in_US__c":"'+eligibleToWorkUS+'",'+
							'"GAP_Grant_Free_or_Reduced_Lunch__c":"'+grantFree+'",'+
							'"Gap_Pell_Grant_Recipient__c":"'+grantPell+'",'+
							'"Parents_Highest_Level_of_education__c":"'+grantParentsHighest+'",'+
							'"Id":"'+"{!actualApplication.Id}"+'"}';
				Visualforce.remoting.Manager.invokeAction(
					'{!$RemoteAction.ProfileSubmitController.savePageOne}',
					app, contact,
					function(result, event){
						if (result == false) {
							if (event.status == true){
								hideSpinner();
								pageOneSaved = true;
								$('#appSaved')[0].style.display = '';
								setTimeout(function() { 
							    	$('#appSaved')[0].style.display = 'none';
								}, 10000);
							} else {
								hideSpinner();
								alert('An error has occured while saving your application');
							}
						} else {
							location.reload();
						}
					})
			}
		}
		$(function(){
			hideElement($('select[id$="gender"]')[0], 'I would like to specify', 'pleaseSpecifySex', 'specifySex');
			hideElement($('select[id$="ethnicity"]')[0], 'Other', 'pleaseSpecifyRace', 'ethnicityDescription');
		})

		function checkCollegeGPA(GPAField){
			if (GPAField.value > 4){
				$("label[id$='collegeGPAErrorLabel']")[0].style.display = '';
				$("label[id$='collegeGPAErrorLabel']")[0].innerHTML = "The GPA must be between 0.0 and 4.0";
				$("input[id$='collegeGPA']")[0].style.borderColor = 'red';
			} else if (!GPAField.checkValidity()){
				$("label[id$='collegeGPAErrorLabel']")[0].style.display = '';
				$("label[id$='collegeGPAErrorLabel']")[0].innerHTML = "The GPA must be of the type 'number.number'";
				$("input[id$='collegeGPA']")[0].style.borderColor = 'red';
			} else {
				$("label[id$='collegeGPAErrorLabel']")[0].style.display = 'none';
				$("input[id$='collegeGPA']")[0].style.borderColor = '';
			}
		}

		function checkHighSchoolGPA(GPAField){
			if (GPAField.value > 4){
				$("label[id$='highSchoolGPAErrorLabel']")[0].style.display = '';
				$("label[id$='highSchoolGPAErrorLabel']")[0].innerHTML = "The GPA must be between 0.0 and 4.0";
				$("input[id$='highSchoolGPA']")[0].style.borderColor = 'red';
			} else if (!GPAField.checkValidity()){
				$("label[id$='highSchoolGPAErrorLabel']")[0].style.display = '';
				$("label[id$='highSchoolGPAErrorLabel']")[0].innerHTML = "The GPA must be of the type 'number.number'";
				$("input[id$='highSchoolGPA']")[0].style.borderColor = 'red';
			} else {
				$("label[id$='highSchoolGPAErrorLabel']")[0].style.display = 'none';
				$("input[id$='highSchoolGPA']")[0].style.borderColor = '';
			}
		}

		var windowOnload = window.onload;
        window.onload = function() {
          if (windowOnload) windowOnload();
          var select = document.getElementById('calYearPicker');
          if (!select) return;
    
          select.innerHTML = '';
          var startYear = new Date().getFullYear() - 50;
          for (var year = startYear; year < startYear + 50; year++) {
            select.options[select.options.length] = new Option(year, year);
          }
        }

        function setGrantFree(value){
        	//var valueToSet = $('input[id*="grantFree"]:checked')[0].value;
        	var grantFreeFields = $('input[id*="grantFree"]')
        	for (var i = 0; i < grantFreeFields.length; i++) {
        		if (grantFreeFields[i].value == value){
        			grantFreeFields[i].checked = true;
        		}
        	}
        }

        function setGrantPell(value){
        	//var valueToSet = $('input[id*="grantFree"]:checked')[0].value;
        	var grantPellFields = $('input[id*="grantPell"]')
        	for (var i = 0; i < grantPellFields.length; i++) {
        		if (grantPellFields[i].value == value){
        			grantPellFields[i].checked = true;
        		}
        	}
        }

        function setParentsHighest(value) {
        	var grantFreeFields = $('input[id*="grantParentsHighest"]')
        	for (var i = 0; i < grantFreeFields.length; i++) {
        		if (grantFreeFields[i].value == value){
        			grantFreeFields[i].checked = true;
        		}
        	}
        }
        
        $(document).ready(function() {
			var numberFields = document.getElementsByClassName('dateInput');
			for (var i = 0; i < numberFields.length; i++) {
				numberFields[i].addEventListener('keydown',function (e) {
					e.preventDefault();
				});
			}
		});
	</script>

	<style>
		.resultsTable {
			background-color: white;
			border: 2px inset grey;
			-webkit-appearance: textfield;
			width: 647px;
			left: 3px;
			top: -17px;
			position: relative;
		}
		a.button {
			-webkit-appearance: button;
			-moz-appearance: button;
			appearance: button;

			text-decoration: none;
			color: initial;
		}
		.dateFormat{
			display: none;
		}
	</style>

	<apex:pageBlock onkeydown="pageOneSaved = false">

<!-- ************************************ 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>
Alain CabonAlain Cabon
Hi Holly,

A first change could be:
 
public class ProfileSubmitController {
...
      @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;                       
        }
    }
}

BillingCity,BillingState and/or City__c, State__c / ShippingCity,ShippingState and so on (according your

Your code is quite big and complicated so the complete validation is not easy. 

Regards
This was selected as the best answer
Holly Havelka 10Holly Havelka 10
Alain - this is what I ended up doing to my component, once I made your suggested changes to the controller:
 
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';
            }
        }
        function fillWithSelectedCollege(element) {

            document.getElementsByClassName('searchBox')[0].value = this.dataset.name;
            document.getElementsByClassName('accId')[0].value = this.dataset.id;
            document.getElementsByClassName('resultsTable')[0].style.display = 'none';
        }

 
Holly Havelka 10Holly Havelka 10
Thanks again for all your help!
Alain CabonAlain Cabon
Good. If your problem is solved, that is an excellent point because you are doing difficult maintenance work currently. You improve your level and develop the skills you need every day.