About

Edit photo

Thursday, February 9, 2017

SOSL Example in Salesforce




system.debug([FIND 'test' IN ALL FIELDS RETURNING  Account (Id,Name,type),Contact(name,email),Opportunity(name,StageName),Lead(company,name,status)]);

Dynamic: The following program search the field com* in account, opportunity and contacts and gets the output in visualforce page.


Apex Class:

public class SOSL {
    public list<account> acclist {set;get;}
    public list<opportunity> opplist {get;set;}
    public list<contact> conlist {get;set;}
    
    public SOSL()
    {
        acclist = new list<account>();
        opplist = new list<opportunity>();
        conlist = new list<contact>();
    }
    
    public void soslMtd()
    {
        list<list<sobject>> searchlist = [find 'com*' in ALL FIELDS RETURNING ACCOUNT (id,name,type),contact(name,email),opportunity(name,stagename)];
        acclist = (list<account>)searchlist[0];
        conlist = (list<contact>)searchlist[1];
        opplist = (list<opportunity>)searchlist[2];
    }
    
    
}

Visualforce Page:
<apex:page controller="SOSL">
    <apex:form>
     <apex:commandButton value="Show records using SOSL" action="{!soslMtd}"/>
        <apex:pageBlock title="accounts">
         <apex:pageBlockTable value="{!acclist}" var="a">
             <apex:column value="{!a.name}"/>
                <apex:column value="{!a.id}"/>
            </apex:pageBlockTable>
        </apex:pageBlock>
        <apex:pageBlock title="contacts">
         <apex:pageBlockTable value="{!conlist}" var="c">
             <apex:column value="{!c.name}"/>
                <apex:column value="{!c.email}"/>
            </apex:pageBlockTable>
        </apex:pageBlock>
        <apex:pageBlock title="opportunity">
         <apex:pageBlockTable value="{!opplist}" var="p">
             <apex:column value="{!p.name}"/>
                <apex:column value="{!p.stagename}"/>
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Output:


0 comments:

Post a Comment