How to search a sObject record using visualforce page

Here is a simple example that searches a standard or custom object record like we do in our salesforce organization's search bar.
After searching record, you can do your custom action like delete, edit etc.

VF Page--

<apex:page controller="AccountSearch">
    <apex:form >
      <apex:pageBlock >
          
              <apex:inputText value="{!searchStr}"/>
              <apex:commandButton action="{!doSearch}" value="Find" reRender="lab"/>
          
      </apex:pageBlock>
      
      <apex:pageBlock >
          <apex:pageBlockTable value="{!acList}" var="ac" id="lab">
              <apex:column headerValue="Name">
                  <apex:outputField value="{!ac.name}"/>
              </apex:column>
              <apex:column headerValue="AccountNumber">
                  <apex:outputField value="{!ac.accountnumber}"/>
              </apex:column>
              <apex:column headerValue="Industry">
                  <apex:outputField value="{!ac.industry}"/>
              </apex:column>
              <apex:column headerValue="Action">
                  <apex:commandLink value="Delete" action="{!deleteRecord}" style="color:red" reRender="lab">
                      <apex:param name="del" value="{!ac.id}" assignTo="{!del}"/>
                  </apex:commandLink>
              </apex:column>
          </apex:pageBlockTable>
      </apex:pageBlock>
  </apex:form>

</apex:page>


Controller


public with sharing class AccountSearch {

    public string searchStr {get;set;}
    public string del {get;set;}
    public List<Account> acList {get;set;}
    
    public void doSearch()
    {       
        acList = [select id,name,accountnumber,industry from account where name =: searchStr];
    }
    
    public void deleteRecord()
    {
        Account acc = [select id from account where id =: del];
        delete acc;
    }

}

Comments

Popular posts from this blog

Dynamically Add/Delete rows in Visualforce Page

Process Automation Specialist Superbadge

How to show or hide a particular section of Visualforce Page dependent upon picklistfield value