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
Holly Havelka 10Holly Havelka 10 

Issue with Dynamic Search Picklist Display

Hi all,

Looking for help on an issue with my controller and visualforce page.

The issue I am having is that the picklist value for 'Interested Technologies' is returning weird results vs. just the name of the account.
User-added image

Here is my controller:
public with sharing class ContactSearchController {

  // the soql without the order and limit
  private String soql {get;set;}
  // the collection of contacts to display
  public List<Contact> contacts {get;set;}
  // the collection of accounts to display
  public Id selectedAccId{get;set;}

  public Boolean IsEmpty {get; set;} 

  // the current sort direction. defaults to asc
  public String sortDir {
    get  { if (sortDir == null) {  sortDir = 'asc'; } return sortDir;  }
    set;
  }

  // the current field to sort by. defaults to last name
  public String sortField {
    get  { if (sortField == null) {sortField = 'lastName'; } return sortField;  }
    set;
  }

  // format the soql for display on the visualforce page
  public String debugSoql {
    get { return soql + ' order by ' + sortField + ' ' + sortDir + ' limit 20'; }
    set;
  }

  // init the controller and display some sample data when the page loads
  public ContactSearchController() {
    soql = 'select firstname, lastname, account.name, interested_technologies__c from contact where account.name != null';
    runQuery();
  }

  // toggles the sorting of query from asc<-->desc
  public void toggleSort() {
    // simply toggle the direction
    sortDir = sortDir.equals('asc') ? 'desc' : 'asc';
    // run the query again
    runQuery();
  }

  // runs the actual query
  public void runQuery() {

    try {
      contacts = Database.query(soql + ' order by ' + sortField + ' ' + sortDir + ' limit 20');
    } catch (Exception e) {
      ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Ooops!'));
    }

  }

  // runs the search with parameters passed via Javascript
  public PageReference runSearch() {

    String firstName = Apexpages.currentPage().getParameters().get('firstname');
    String lastName = Apexpages.currentPage().getParameters().get('lastname');
    String accountName = Apexpages.currentPage().getParameters().get('accountName');
    String technology = Apexpages.currentPage().getParameters().get('technology');

    soql = 'select firstname, lastname, account.name, interested_technologies__c from contact where account.name != null';
    if (!firstName.equals(''))
      soql += ' and firstname LIKE \''+String.escapeSingleQuotes(firstName)+ '%\'';
    if (!lastName.equals(''))
      soql += ' and lastname LIKE \''+String.escapeSingleQuotes(lastName)+ '%\'';
    if (!accountName.equals(''))
      soql += ' and account.name LIKE \''+String.escapeSingleQuotes(accountName)+ '%\'';  
    if (!technology.equals(''))
      soql += ' and interested_technologies__c includes (\''+technology+'\')';

    // run the query again
    runQuery();

    return null;
  }

  // use apex describe to build the picklist values
  public List<String> technologies {
    get {
      if (technologies == null) {

        technologies = new List<String>();
        Schema.DescribeFieldResult field = Contact.interested_technologies__c.getDescribe();

        for (Schema.PicklistEntry f : field.getPicklistValues())
          technologies.add(f.getLabel());

      }
      return technologies;          
    }
    set;
  }

  /*public List<String> options {
    get {
      if (options == null) {

        options = new List<String>();
        Schema.DescribeFieldResult field = Account.Name.getDescribe();

        for (Schema.PicklistEntry f : field.getPicklistValues())
          options.add(f.getLabel());

      }
      return options;          
    }
    set;
  }*/
  
  //builds a picklist of account names based on their account id

  public List<selectOption> getaccts() {

      List<selectOption> options = new List<selectOption>(); 
  //new list for holding all of the picklist options
      options.add(new selectOption('', '- None -')); 
  //add the first option of '- None -' in case the user doesn't want to select a value or in case no values are returned from query below
      for (Account account : [SELECT Id, Name FROM Account]) { 
  //query for Account records 
          options.add(new selectOption(account.Name, account.Name)); 
  //for all records found - add them to the picklist options
      }
      return options; //return the picklist options
  }

}
Here is my visualforce page:
<apex:page controller="ContactSearchController" sidebar="false">

  <apex:form >
  <apex:pageMessages id="errors" />

  <apex:pageBlock title="Search Collaborative Wide Staff Directory" mode="edit">

  <table width="100%" border="0">
  <tr>  
    <td width="200" valign="top">

      <apex:pageBlock title="Search Properties" mode="edit" id="criteria">

      <script type="text/javascript">
      function doSearch() {
        searchServer(
          document.getElementById("firstName").value,
          document.getElementById("lastName").value,
          document.getElementById("accountName").value,
          document.getElementById("technology").options[document.getElementById("technology").selectedIndex].value
          );
      }
      </script> 

      <apex:actionFunction name="searchServer" action="{!runSearch}" rerender="results,debug,errors">
          <apex:param name="firstName" value="" />
          <apex:param name="lastName" value="" />
          <apex:param name="accountName" value="" />
          <apex:param name="technology" value="" />
      </apex:actionFunction>

      <table cellpadding="2" cellspacing="2">
      <tr>
        <td style="font-weight:bold;">First Name<br/>
        <input type="text" id="firstName" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">Last Name<br/>
        <input type="text" id="lastName" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">Account<br/>
        <input type="text" id="accountName" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">Interested Technologies<br/>
          <select id="technology" onchange="doSearch();">
            <option value=""></option>
            <apex:repeat value="{!accts}" var="tech">
              <option value="{!tech}">{!tech}</option>
            </apex:repeat>
          </select>
        </td>
      </tr>
      </table>

      <!--<apex:pageBlockSection title="Custom Picklist Using selectList and selectOptions">
          <apex:selectList value="{!options}" multiselect="false" size="1">
                  <apex:selectOptions value="{!accts}"/>
          </apex:selectList>
      </apex:pageBlockSection>-->

      </apex:pageBlock>

    </td>
    <td valign="top">

    <apex:pageBlock mode="edit" id="results">

        <apex:pageBlockTable value="{!contacts}" var="contact">

            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="First Name" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="firstName" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!contact.firstName}"/>
            </apex:column>

            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Last Name" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="lastName" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!contact.lastName}"/>
            </apex:column>

            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Account" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="account.name" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!contact.account.name}"/>
            </apex:column>

            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Technologies" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="interested_technologies__c" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!contact.interested_technologies__c}"/>
            </apex:column>

        </apex:pageBlockTable>

    </apex:pageBlock>

    </td>
  </tr>
  </table>

  <apex:pageBlock title="Debug - SOQL" id="debug">
      <apex:outputText value="{!debugSoql}" />           
  </apex:pageBlock>    

  </apex:pageBlock>

  </apex:form>

</apex:page>
What am I missing?   Any help is much appreciated.

 
Best Answer chosen by Holly Havelka 10
Nayana KNayana K
<apex:repeat value="{!accts}" var="tech">
              <option value="{!tech.value}">{!tech.label}</option>
            </apex:repeat>

Please try this once.

All Answers

Nayana KNayana K
<apex:repeat value="{!accts}" var="tech">
              <option value="{!tech.value}">{!tech.label}</option>
            </apex:repeat>

Please try this once.
This was selected as the best answer
Holly Havelka 10Holly Havelka 10
Nayana!  That worked.  Thank you so much.  Follow-up/Learning question: before I was passing the whole string through?  Now, I am only passing through the label, correct?
Nayana KNayana K
{!tech} is instance of SelectOption. <option> tag thinks it as a string for value attribute. SelectOption has getter methods ( getValue()  <==> {!tech.value} at VF page side, getLabel()  <==> {!tech.label} at VF page side) .
https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/apex_System_SelectOption_methods.htm
SFDC_biSFDC_bi
I have problem with my Picklist. Picklist search is not working.

Below is my code;
VF page:
<apex:page sidebar="false" showHeader="false" controller="AccoutSearchController_New">
<apex:actionstatus id="actStatus">
        <apex:facet name="start">
            <div class="waitingSearchDiv" id="el_loading" style="background-color: #fbfbfb; height:100%;opacity:0.65;width:100%;">
                <div class="waitingHolder" style="top: 100px; width: 91px;">
                <img class="waitingImage" src="/img/loading.gif" title="Please Wait..." />
                <span class="waitingDescription">Loading...</span>
                </div>
            </div>
        </apex:facet>
    </apex:actionstatus>
<apex:form >
  <apex:pageMessages id="errors" />
  
  <apex:pageBlock title="Search Company!" mode="edit">
    
  <table width="100%" border="0">
  <tr>  
    <td width="200" valign="top">
  
      <apex:pageBlock title="Enter Details" mode="edit" id="criteria">
      
      <script type="text/javascript">
      function doSearch() {
           searchServer(
           document.getElementById("companyname").value,
           document.getElementById("accno").value,
           document.getElementById("billcity").value,
           document.getElementById("acctypes").options[document.getElementById("acctypes").selectedIndex].value);

      }
      </script> 
      
      <apex:actionFunction name="searchServer" action="{!runSearch}" rerender="results,debug,errors">
          <apex:param name="companyname" value="" />
          <apex:param name="accno" value="" />
          <apex:param name="billcity" value="" />
          <apex:param name="type" value="" />
      </apex:actionFunction>
          
      <table cellpadding="2" cellspacing="2">
      <tr>
        <td style="font-weight:bold;">Company Name<br/>
        <input type="text" id="companyname" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">Account No<br/>
        <input type="text" id="accno" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">City<br/>
        <input type="text" id="billcity" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">Company Type<br/>
         <select id="type" onchange="doSearch();">
            <option value="">None</option>
            <apex:repeat value="{!acctypes}" var="acts">
              
               <option value="{!acts}">{!acts}</option> 
            </apex:repeat>
          </select>
        </td>
      </tr> 
      </table>
      
      </apex:pageBlock>
  
    </td>
    <td valign="top">
    
    <apex:pageBlock mode="edit" id="results">
    <apex:outputPanel rendered="false" >
    <apex:commandButton value="Select" status="actStatus" action="{!selectAcct}" reRender="pg"/>
    </apex:outputPanel>
                
         <apex:pageBlockTable value="{!accounts}" var="acc">
                
        <apex:column width="35px">
        <apex:facet name="header">
        Select
         </apex:facet>
         <apex:inputCheckbox />
         </apex:column>
            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Company Name" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="name" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!acc.name}"/>
            </apex:column> 
            
            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Account No" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="accno" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!acc.AccountNumber}"/>
            </apex:column>
            
            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="City" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="account.BillingCity" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!acc.BillingCity}"/>
            </apex:column>
            
            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Account Types" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="Account Type" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!acc.Type}"/>
            </apex:column>
       
        </apex:pageBlockTable>
        

               
    </apex:pageBlock>
    
    </td>
  </tr>
  </table>
  
  </apex:pageBlock>

  </apex:form>

</apex:page>

Controller:
 
public with sharing class AccoutSearchController_New {

    

    public String controller { get; set; }

    
  
  // the soql without the order and limit
  private String soql {get;set;}
  // the collection of contacts to display
  public List<Account> accounts {get;set;}
  
  // the current sort direction. defaults to asc
  public String sortDir {
    get  { if (sortDir == null) {  sortDir = 'asc'; } return sortDir;  }
    set;
  }
  
  // the current field to sort by. defaults to last name
  public String sortField {
    get  { if (sortField == null) {sortField = 'name'; } return sortField;  }
    set;
  }
  
  // format the soql for display on the visualforce page
  public String debugSoql {
    get { return soql + ' order by ' + sortField + ' ' + sortDir + ' limit 5'; }
    set;
  }

  // init the controller and display some sample data when the page loads
  public AccoutSearchController_New () {
    soql = 'select id,name,AccountNumber,Type,BillingCity from Account where name != null';
    runQuery();
  }
  
  // toggles the sorting of query from asc<-->desc
  public void toggleSort() {
    // simply toggle the direction
    sortDir = sortDir.equals('asc') ? 'desc':'asc';
    // run the query again
    runQuery();
  }
  
  public void selectAcct() {
       
            }
    

  
  // runs the actual query
  public void runQuery() {
        
    try {
      system.debug('');
      accounts = Database.query(soql + ' order by ' + sortField + ' ' + sortDir + ' limit 99');
      

    } catch (Exception e) {
      ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Ooops!'));
    }

  }
  
  // runs the search with parameters passed via Javascript
  public PageReference runSearch() {
    
    String companyname = Apexpages.currentPage().getParameters().get('companyname');
    String accno = Apexpages.currentPage().getParameters().get('accno');
    String acctype = Apexpages.currentPage().getParameters().get('acctype');
    String billcity = Apexpages.currentPage().getParameters().get('billcity');
    
    soql = 'select name,AccountNumber,Type,BillingCity from account where name != null';
    
   // if (!String.isEmpty(companyname))
   //   soql += ' and companyname LIKE \''+String.escapeSingleQuotes(companyname)+'%\'';  
      
    if (!companyname.equals(''))
     soql += ' and name LIKE \''+String.escapeSingleQuotes(companyname)+'%\'';

    
   // if (!String.isEmpty(accno))
   //   soql += ' and AccountNumber LIKE \''+String.escapeSingleQuotes(accno)+'%\'';    
      
      if (!accno.equals(''))
      soql += ' and AccountNumber LIKE \''+String.escapeSingleQuotes(accno)+'%\'';
     
      
   // if (!String.isEmpty(billcity))
   // soql += ' and BillingCity LIKE \''+String.escapeSingleQuotes(billcity)+'%\'';      
    
    if (!billcity.equals(''))
     soql += ' and BillingCity LIKE \''+String.escapeSingleQuotes(billcity)+'%\'';
      
     if (!String.isEmpty(acctype))
      soql += ' and type=\''+acctype+'\''; 
      
  // if (!acctype.equals(''))
    
  //  soql += ' and type incluldes (\''+acctype +'\'')'; 
     
    
  

    // run the query again
    runQuery();

    return null;
  }
  
  // use apex describe to build the picklist values
  public List<String> acctypes {
    get {
      if (acctypes == null) {
              
        acctypes = new List<String>();
        Schema.DescribeFieldResult field = account.type.getDescribe();
            
        for (Schema.PicklistEntry f : field.getPicklistValues())
          if(f.getLabel()=='Prospect' || f.getLabel()=='Customer - Direct')
              acctypes.add(f.getLabel());
          
      }
      return acctypes;          
    }
    set;
  }

}

Appreciate your help! 
SFDC_biSFDC_bi
@Nayana K. can you please reply on this