Monday 20 January 2014

Wild card search in soql

Use like operator along with % character in where clause of SOQL to implement wildcard search. In the following example query returns account records matching inputtext with account name. %'input string'% in where clause returns all the accounts having the input string anywhere in the account name. For ex.if the input string is 'tech' , query will return account with names 'Willsinfotech' and also 'infotech solutions'

Visualforce
<apex:page controller="wildcardController">
  <apex:form >
    <apex:pageblock >
        <apex:inputtext value="{!inputtext}"/>
        <apex:commandbutton value=" Search " action="{!searchRecords}"/>
    </apex:pageblock>
    <apex:pageblock rendered="{!flagshow}">
      <apex:pageblocktable value="{!accList}" var="acc">
        <apex:column value="{!acc.name}"/>
        <apex:column value="{!acc.accountnumber}"/>
      </apex:pageblocktable>
    </apex:pageblock>
  </apex:form>
</apex:page>

Controller
Public class wildcardController {
    Public string inputtext{get;set;}
    Public List<account> accList{get;set;}
    Public boolean flagshow{get;set;}
    Public wildcardController(){
     flagshow = false;
    }    
    Public void searchRecords(){
     flagshow = true;
      accList = database.Query('select name,accountnumber from account where name like '+'\''+'%'+inputtext+'%'+'\'');
    }
}

No comments:

Post a Comment