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
CBBsfdcCBBsfdc 

Design a Visualforce Page which would allow the Users to enter a keyword and search for all the Contacts, Leads and Accounts which match the keyword.

Best Answer chosen by CBBsfdc
Raj VakatiRaj Vakati
Use this code
 
apex:page controller="SOSLdemoExample">
<apex:form >
<apex:inputText value="{!searchStr}"/>
<apex:commandButton value="Search in Account, Contact, Opportunity" action="{!soslSearchmethod }"   reRender="acct,error,oppt,cont" status="actStatusId"/>
<apex:actionStatus id="actStatusId">
<apex:facet name="start" >
<img src="/img/loading.gif"/>
</apex:facet>
</apex:actionStatus>
</apex:form>
<apex:outputPanel title="" id="error">
<apex:pageMessages ></apex:pageMessages>
</apex:outputPanel>
<apex:pageBlock title="Accounts" id="acct">
<apex:pageblockTable value="{!accList }" var="acc">
<apex:column value="{!acc.name}"/>
<apex:column value="{!acc.Type}"/>
</apex:pageblockTable>
</apex:pageBlock>
<apex:pageBlock title="Contacts" id="cont">
<apex:pageblockTable value="{!conList}" var="con">
<apex:column value="{!con.name}"/>
<apex:column value="{!con.email}"/>
</apex:pageblockTable>
</apex:pageBlock>
<apex:pageBlock title="Opportunities" id="oppt">
<apex:pageblockTable value="{!optyList}" var="opty">
<apex:column value="{!opty.name}"/>
<apex:column value="{!opty.StageName}"/>
</apex:pageblockTable>
</apex:pageBlock>
</apex:page>
Public with sharing class SOSLdemoExample{
 Public List<Opportunity> optyList {get;set;}
 Public List<contact> conList{get;set;}
 Public List<account> accList{get;set;}

 Public String searchStr{get;set;}
   Public SOSLdemoExample(){
   }

  Public void soslSearchmethod (){
   optyList = New List<Opportunity>();
   conList = New List<contact>();
   accList = New List<account>();
   if(searchStr.length() > 2){
   String searchStr1 = '*'+searchStr+'*';
   String searchQuery = 'FIND \'' + searchStr1 + '\' IN ALL FIELDS RETURNING  Account (Id,Name,type),Contact(name,email),Opportunity(name,StageName)';
   List<List <sObject>> searchList = search.query(searchQuery);
   accList = ((List<Account>)searchList[0]);
   conList  = ((List<contact>)searchList[1]);
   optyList = ((List<Opportunity>)searchList[2]);
   if(accList.size() == 0 && conList.size() == 0 && optyList.size() == 0){
       apexPages.addmessage(new apexpages.message(apexpages.severity.Error, 'Sory, no results returned with matching string..'));
       return;
   }
   }
   else{
   apexPages.addmessage(new apexpages.message(apexpages.severity.Error, 'Please enter at least three characters..'));
   return;
   }
  }
}