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
veeru_pariveeru_pari 

problem in Search functionality

Hi ,
i have search code below  where i can search a question with its beginning letter or if i give full question but i want to get the question even  if i given any letter  or word in middile of that question. please help me on this .I hope there might be wrong in like condition.Can i please know how can i solve this?

Here is the code for that
Vf page
<apex:page controller="QuesSearchCont" sidebar="false">
<apex:form >
  <apex:pageMessages id="errors" />

  <apex:pageBlock title="Find Me A Question & Answer!" mode="edit">

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

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

      <script type="text/javascript">
      function doSearch() {
        searchServer(
          document.getElementById("question").value,
          document.getElementById("answer").value);
      }
      </script>

      <apex:actionFunction name="searchServer" action="{!runSearch}" rerender="results,debug,errors">
          <apex:param name="Question__c" value="" />
          <apex:param name="Answer__c" value="" />
       
       
      </apex:actionFunction>

      <table cellpadding="0" cellspacing="0">
      <tr>
        <td style="font-weight:bold;">QUESTION<br/>
        <input type="text" id="question" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">ANSWER<br/>
       <input type="text" id="answer" onkeyup="doSearch();"/>
        </td>
      </tr>
            </table>

      </apex:pageBlock>

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

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

        <apex:pageBlockTable value="{!faq}" var="faqs">

            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Question" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="question" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
              <apex:outputField value="{!faqs.Question__c}"/>
            </apex:column>

            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Answer" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="answer" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
               <apex:outputField value="{!faqs.Answer__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>

Controler:public with sharing class QuesSearchCont {
// the soql without the order and limit
private String soql {get;set;}
  // the collection of contacts to display
  public List<FAQ__c> faq {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 = 'Question__c'; } 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 QuesSearchCont() {
    soql = 'select Question__c, Answer__c from FAQ__c where Question__c!= 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 {
      faq = Database.query(soql + ' order by ' + sortField + ' ' + sortDir + ' limit 20');
    } catch (Exception e) {
      ApexPages.addMessages(e);
    }

  }

  // runs the search with parameters passed via Javascript
  public PageReference runSearch() {
try{
FAQ__c f=new FAQ__c();
    String question = Apexpages.currentPage().getParameters().get('Question__c');
    String answer = Apexpages.currentPage().getParameters().get('Answer__c');
 

  
    soql = 'select Question__c, Answer__c from FAQ__c where Question__c!= null';
    if (!question.equals(''))
      soql += ' and Question__c LIKE \''+String.escapeSingleQuotes(question)+'%\'';
    if (!answer.equals(''))
      soql += ' and Answer__c LIKE \''+String.escapeSingleQuotes(answer)+'%\'';
   // if (!accountName.equals(''))
     // soql += ' and account.name LIKE \''+String.escapeSingleQuotes(accountName)+'%\'';
  
    // run the query again
    }
     catch(NullPointerException ne){
     ApexPages.addMessages(ne);
    }
    runQuery();

    return null;
    }



}
Best Answer chosen by veeru_pari
DevADSDevADS
Hey Veeru_Pari,

Put '%' in Prefix also whenver you search Question__c like \'%'+searchstring+'%\'. 

so change your soql  string to:
soql = 'select Question__c, Answer__c from FAQ__c where Question__c!= null';
    if (!question.equals(''))
      soql += ' and Question__c LIKE 
\'%'+String.escapeSingleQuotes(question)+'%\'';
    if (!answer.equals(''))
      soql += ' and Answer__c LIKE \'%'+String.escapeSingleQuotes(answer)+'%\'';


Happy Coding!!

All Answers

DevADSDevADS
Hey Veeru_Pari,

Put '%' in Prefix also whenver you search Question__c like \'%'+searchstring+'%\'. 

so change your soql  string to:
soql = 'select Question__c, Answer__c from FAQ__c where Question__c!= null';
    if (!question.equals(''))
      soql += ' and Question__c LIKE 
\'%'+String.escapeSingleQuotes(question)+'%\'';
    if (!answer.equals(''))
      soql += ' and Answer__c LIKE \'%'+String.escapeSingleQuotes(answer)+'%\'';


Happy Coding!!
This was selected as the best answer
veeru_pariveeru_pari
Hi amit,
Thank u very much it solved my prob.
DevADSDevADS
Hi Veeru,

Great!!! My pleasure! :D
veeru_pariveeru_pari
Hi Amit, I have other query where i have a custom object in that i have fields questions(data type text area),answers(answer also same ) an pick list having internal user,external user and All users. now my requirement is i want to display the pick list values in vf page and if the user selects internal option in picklist then page shpuld display question and answer related to internal and if he selects all it should display all the ques and answers. Will you u please tell me how to achieve this req Thanks in advance Veeraiah
DevADSDevADS
You can do it using SelectList. Whenever the User will click on Search Buttion, You will Query on object Where the the use will be of type the selected picklist field. Here you will get List<Custom_Object> records which will have questions & answers of the slected picklist type. Just show this list on VF page.


1) public List<String> selectedValue {get;set;}
public List<SelectOption> getUserType()
{
  List<SelectOption> options = new List<SelectOption>();
      
   Schema.DescribeFieldResult fieldResult =CustomObject__c.getUserType__c.getDescribe();
   List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
      
   for( Schema.PicklistEntry f : ple)
   {
      options.add(new SelectOption(f.getLabel(), f.getValue()));
   }     
   return options;
}

With our controller logic all complete, we can call the getUserType() method from our Visualforce page,  and populate the <apex:selectList> tag:

2) <apex:selectList id="countries" value="{selectedValue}"
         size="1" required="true">
  <apex:selectOptions value="{!countries}"/>
</apex:selectList>

3) You will query in that Custom object when the Search button will be click with selectedValue which will return of list of records. Now rerender the form or Outputpanel.

Let me know if you didn't understand the scenario or any query. Happy Coding!!!
veeru_pariveeru_pari
yes amit i havent understood the scenario..could u please explain me in detail Thanks in advance...
DevADSDevADS
Hey Veeru,

I am just giving you the template. Change your code with template

Controller :
public class VEERU_PageController{

    public String selectedValue {get;set;}
    public List<SelectOption> getUserType()
    {
        List<SelectOption> options = new List<SelectOption>();
        Schema.DescribeFieldResult fieldResult = Book__c.UserType__c.getDescribe();
        List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues(); // Here you will get the picklist values
        options.add(new SelectOption('All','All'));
        for( Schema.PicklistEntry f : ple)
        {
            options.add(new SelectOption(f.getLabel(), f.getValue()));
        }   
        return options;
    }
  
    public List<Book__c> search(){
        System.debug('====selectedValue===='+selectedValue); // You will get the Selected Value here
        List<Book__c> temp = new List<Book__c>();
        String queryString;
        if(selectedValue == 'ALL') queryString ='SELECT id,Question__c,Answer__c from CustomObject__c';
        else if(selectedValue == 'Internal') queryString ='SELECT id,Question__c,Answer__c from CustomObject__c WHERE UserType__c = 'Internal'';
        else if(selectedValue == 'External') queryString ='SELECT id,Question__c,Answer__c from CustomObject__c WHERE UserType__c = 'External'';
        temp = Database.query(queryString);
        return temp;
    }
}

Page
<apex:page controller="VEERU_PageController">
  <apex:form id="form1">
    <apex:selectList id="countries" value="{!selectedValue}"
    size="1" required="true">
        <apex:selectOptions value="{!UserType}"/>
    </apex:selectList>
    <apex:commandButton value="Search" action="{!search}" rerender="form1"/>
    <!--  Take table here & display your record 
      -->
    </apex:form>
</apex:page>

Hope this will help, If you still facing any issues, let me know! Happy Coding!!
veeru_pariveeru_pari
Hi amith, I have customized the code to my requirement i am getting the error Comparison arguments must be compatible types: LIST, String at line 20 column 7 In my code line 20 is the code where i have underline *public List search(){ System.debug('====selectedValue===='+selectedValue); // You will get the Selected Value here List temp = new List(); String queryString; if(selectedValue == 'ALL') queryString ='SELECT id,Question__c,Answer__c from CustomObject__c'; else if(selectedValue == 'Internal') queryString ='SELECT id,Question__c,Answer__c from CustomObject__c WHERE UserType__c = 'Internal''; else if(selectedValue == 'External') queryString ='SELECT id,Question__c,Answer__c from CustomObject__c WHERE UserType__c = 'External''; temp = Database.query(queryString); return temp; }* *what is the error about?* Thanks
DevADSDevADS
Hey,

It  seems all correct to me, I am also not facing the compatibility error. May be you know this that the error is occuring due to the LHS & RHS of Assignment operator is different. Check your code or Share your code.
Happy Coding!!
veeru_pariveeru_pari
Hi Amith, In the below code if i try to run i am getting. the error like this (FAQCu Compile Error: Comparison arguments must be compatible types: LIST, String at line 20 column 12)I have hilighted the errior in bold letters in the below code public class FAQCu { public List selectedValue {get;set;} public List getUserType() { List options = new List(); Schema.DescribeFieldResult fieldResult =FAQ__c.Users__c.getDescribe(); List ple = fieldResult.getPicklistValues(); // options.add(new SelectOption('All','All')); for( Schema.PicklistEntry f : ple) { options.add(new SelectOption(f.getLabel(), f.getValue())); } return options; } public List getSearch(){ System.debug('====selectedValue===='+selectedValue); // You will get the Selected Value here List temp = new List(); String queryString; * Line 20// if(selectedValue=='AllUsers') * queryString='SELECT Users__c,Question__c,Answer__cfrom FAQ__c WHERE Users__c =AllUsers'; else if(selectedValue=='InternalUsers') queryString='SELECT Users__c,Question__c,Answer__c from FAQ__c WHERE Users__c =InternalUsers'; else if(selectedValue=='ExternalUsers') queryString='SELECT Users__c,Question__c,Answer__c from FAQ__c WHERE Users__c =ExternalUsers'; temp = Database.query(queryString); return temp; } } and the vf page is: Thanks Veeraiah On Thu, Jan 9, 2014 at 5:49 PM, veeru chowdary wrote:
veeru_pariveeru_pari
Hi , I'd like to add you to my professional network on LinkedIn. - veeraiah Accept: https://www.linkedin.com/e/v2?e=26hmgj-hxn5axcy-5q&a=preRegInvite&tracking=eml-guest-invite-cta&ek=invite_guest&invitationID=5894776477383147521&sharedKey=IpX-D5Xl You are receiving Invitation emails. Unsubscribe here: https://www.linkedin.com/e/v2?e=26hmgj-hxn5axcy-5q&t=uns&tracking=eml-guest-invite-unsubscribe&ek=invite_guest&id=20061∣=-1&aid=iuehc9r3r0sm6r3&eid=26hmgj-hxn5axcy-5q&email=0-5d8znenhfwceb5%2Esa98wemt94wc1rkt%40i2kklu1rgvxgcveo%2Ez3b65z%2Ef-55kkmai%2Ena10%2Echatter%2Esalesforce%2Ecom Learn why we included this at the following link: http://www.linkedin.com/e/v2?e=26hmgj-hxn5axcy-5q&a=customerServiceUrl&ek=invite_guest&articleId=4788 © 2014, LinkedIn Corporation. 2029 Stierlin Ct. Mountain View, CA 94043, USA
veeru_pariveeru_pari
Hi , I'd like to add you to my professional network on LinkedIn. - veeraiah Accept: https://www.linkedin.com/e/v2?e=-1wovlk-hxn5ax5t-3u&a=preRegInvite&tracking=eml-guest-invite-cta&ek=invite_guest&invitationID=5894776474518446080&sharedKey=XkFpD_2x You are receiving Invitation emails. Unsubscribe here: https://www.linkedin.com/e/v2?e=-1wovlk-hxn5ax5t-3u&t=uns&tracking=eml-guest-invite-unsubscribe&ek=invite_guest&id=20061∣=-1&aid=iuehc9r3r0sm6r3&eid=-1wovlk-hxn5ax5t-3u&email=427f6nwsi4lmzwco%2E37mcdthb03gxbjr4%40qnls2yf9ko312xm7%2Eajyep%2Ef-55kkmai%2Ena10%2Echatter%2Esalesforce%2Ecom Learn why we included this at the following link: http://www.linkedin.com/e/v2?e=-1wovlk-hxn5ax5t-3u&a=customerServiceUrl&ek=invite_guest&articleId=4788 © 2014, LinkedIn Corporation. 2029 Stierlin Ct. Mountain View, CA 94043, USA
veeru_pariveeru_pari
Hi , I'd like to add you to my professional network on LinkedIn. - veeraiah Accept: https://www.linkedin.com/e/v2?e=-7fo6v9-hxn5axcf-18&a=preRegInvite&tracking=eml-guest-invite-cta&ek=invite_guest&invitationID=5894776476338769920&sharedKey=qFsUyGHW You are receiving Invitation emails. Unsubscribe here: https://www.linkedin.com/e/v2?e=-7fo6v9-hxn5axcf-18&t=uns&tracking=eml-guest-invite-unsubscribe&ek=invite_guest&id=20061∣=-1&aid=iuehc9r3r0sm6r3&eid=-7fo6v9-hxn5axcf-18&email=48oi0nwglr5wvb0j%2Ecm2uyp0zyya4otdp%40u1tfn8c303ky32b9%2Eouooa%2Ef-55kkmai%2Ena10%2Echatter%2Esalesforce%2Ecom Learn why we included this at the following link: http://www.linkedin.com/e/v2?e=-7fo6v9-hxn5axcf-18&a=customerServiceUrl&ek=invite_guest&articleId=4788 © 2014, LinkedIn Corporation. 2029 Stierlin Ct. Mountain View, CA 94043, USA