Search data in multiple objects at the same time using SOSL - Apex Example #inSalesforce

Search data in multiple objects at the same time using SOSL - Apex Example #inSalesforce


<apex:page controller="theController">
    <apex:form>
        <apex:inputText value="{!searchString}"/>
        <apex:commandButton value="Get Records" action="{!Search}"/>
        <br/>
        <br/>
        <apex:pageBlock title="Accounts">
            <apex:pageblockTable value="{!aList}" var="a">
                <apex:column value="{!a.Name}"/>
                <apex:column value="{!a.Type}"/>
            </apex:pageblockTable>
        </apex:pageBlock>
        <apex:pageBlock title="Contacts">
            <apex:pageblockTable value="{!cList}" var="c">
                <apex:column value="{!c.Name}"/>
                <apex:column value="{!c.Phone}"/>
            </apex:pageblockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>



public class theController{
    Public List<Contact> cList {get; set;}
    Public List<Account> aList {get; set;}
    Public String searchString {get; set;}
    Public void Search(){
        cList = New List<contact>();
        aList = New List<account>();
        List<List <sObject>> searchList = [FIND :searchString IN ALL FIELDS RETURNING  Account (Id,Name,Type), Contact(Name,Phone)];
        aList = ((List<account>)searchList[0]);
        cList  = ((List<contact>)searchList[1]);
    }
}

Comments