Sunday, April 13, 2014

What is SOSL in Apex?

What is SOSL in Apex?


Salesforce Object Search Language (SOSL) is a simple language for searching across all multiple persisted objects simultaneously.
  1. Sosl statements evaluate to a list of SObjects where each list contains the search results for a particular sobject type.
  2. SOSL queries are only supported in apex classes and anonymous blocks.
  3. We can not use a SOSL query in trigger.

EX:-
The following example that searches all fields across all account and contact objects.

List<List< Sobject>> searchList = [FIND ‘Text*’  IN ALL FIELDS RETURNING Account,Contact];
system.debug(‘searchlist is :’+searchList );

Ex2 : - The Example shows the data with test in Accounts,Contacts,Leads,Oppotunities with Vf page.

Vf  Page :-

<apex:page controller="DeferenceDemoController">
 <apex:form >
    <apex:commandButton value="Show records using SOSL" action="{!soslDemo_method}"/>
    <apex:pageBlock title="Accounts">
      <apex:pageblockTable value="{!accList }" var="acc">
         <apex:column value="{!acc.name}"/>
         <apex:column value="{!acc.Type}"/>
      </apex:pageblockTable>
    </apex:pageBlock>
<apex:pageBlock title="Contacts">
    <apex:pageblockTable value="{!conList}" var="con">
     <apex:column value="{!con.name}"/>
     <apex:column value="{!con.email}"/>
</apex:pageblockTable>
</apex:pageBlock>
<apex:pageBlock title="Leads">
    <apex:pageblockTable value="{!leaList}" var="lea">
     <apex:column value="{!lea.name}"/>
     <apex:column value="{!lea.company}"/>
    </apex:pageblockTable>
</apex:pageBlock>
<apex:pageBlock title="Opportunities">
    <apex:pageblockTable value="{!optyList}" var="opty">
     <apex:column value="{!opty.name}"/>
    <apex:column value="{!opty.StageName}"/>
</apex:pageblockTable>
</apex:pageBlock>
 </apex:form>
</apex:page>

Apex Controller :-

Public with sharing class DeferenceDemoController {
Public List<Opportunity> optyList {get;set;}
Public List<Lead> leaList{get;set;}
Public List<contact> conList{get;set;}
Public List<account> accList{get;set;}
  Public DeferenceDemoController(){
  }
 Public void soslDemo_method(){
  optyList = New List<Opportunity>();
  leaList = New List<Lead>();
  conList = New List<contact>();
  accList = New List<account>();
  List<List <sObject>> searchList = [FIND 'test' IN ALL FIELDS RETURNING  Account (Id,Name,type),Contact(name,email),Opportunity(name,StageName),Lead(company,name,status) ];
  accList = ((List<Account>)searchList[0]);
  conList  = ((List<contact>)searchList[1]);
  optyList = ((List<Opportunity>)searchList[2]);
  leaList  = ((List<Lead>)searchList[3]);
 }
}






1 comments:

nick jones said...


thanks for sharing..
Server and Storage

Post a Comment

 
| ,