Monday, December 30, 2013

Search Page in Visualforce-Simplified

Here is a simple example how to build a simple Visualforce search page. When I started learning Visualforce I thought building a search page is too complex, but it's not true. We can modify the wrapper class example which I posted earlier to achieve this. Nothing much to dig deeper into the code. The code is very simple just passing the get set parameters from a text field to the controller query using the 'LIKE'clause. Here is the controller for it to give you a clear picture.

 public with sharing class accsearchcontroller {  
   public list <account> acc {get;set;}  
   public string searchstring {get;set;}  
   public accsearchcontroller(ApexPages.StandardController controller) {  
   }  
   public void search(){  
     string searchquery='select name,id from account where name like \'%'+searchstring+'%\' Limit 20';  
     acc= Database.query(searchquery);  
   }  
   public void clear(){  
   acc.clear();  
   }  
 }  

    let's see what I have done here. I have created a string variable searchstring and used the variable in the LIKE query. This search string gets the input from the text box in the visualforce page where user will enter the data and again passes the query string variable inside the database.query() method. If you look at the visual force page code

 <apex:page standardController="account" extensions="accsearchcontroller">  
  <apex:form >  
 <apex:inputText value="{!searchstring}" label="Input"/>   
  <apex:commandButton value="Search records" action="{!search}"/>  
  <apex:commandButton value="Clear records" action="{!search}"/>  
   <apex:pageBlock title="Search Result">  
    <apex:pageblockTable value="{!acc}" var="a">  
     <apex:column >  
      <apex:outputlink value="https://ap1.salesforce.com/{!a.id}">{!a.Name}</apex:outputlink>  
     </apex:column>  
     <apex:column value="{!a.id}"/>  
    </apex:pageBlockTable>     
   </apex:pageBlock>   
  </apex:form>  
 </apex:page>  



Here is the button action method "Search" which returns the list of records. It's simple isn't it?