How to Build a Simple Visualforce Page for Searching Records

How to Build a Simple Visualforce Page for Searching Records

Hello guys,

Today, I am showing you how you can build a Simple Visualforce Page for searching records. I am using string named as search key to the controller using {get; set:} query using the ‘LIKE’ clause. display the result using in visualforce page.
This search key gets its input from the data entered by the user in the text box in the visualforce page. The search key passes the query into the function in the controller which uses Database.query().

VisualForce Page:-

<apex:page Controller="SearchInVFController">
    <apex:form>
        <apex:inputText value="{!searchKey}" label="Input"/>
        <apex:commandButton value="Search records" action="{!search}"/>
        <apex:commandButton value="Clear records" action="{!clear}"/>
        <apex:pageBlock title="Search Result">
            <apex:pageBlockTable value="{!acc}" var="a">
                <apex:column value="{!a.name}"/>
                <apex:column value="{!a.id}"/>
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Apex controller-

public class SearchInVFController {
    public list <Account> acc {get;set;}
    public String searchKey {get;set;}
    public SearchInVFController( ) {
    }
    public void search(){
        string searchquery='select Name,id from account where name like \'%'+searchKey+'%\' Limit 10';
        acc= Database.query(searchquery);
    }
    public void clear(){
        acc.clear();
    }
}

Output-

Thanks.

Happy coding

Popular Salesforce Blogs