Tag Archives: Salesforce

Salesforce SOSL Example

  • SOSL (Salesforce Object Search Language) is a search language in Salesforce, we can search in multiple objects at same time using SOSL. In SOQL, we can query only one object at a time but in SOSL, We can search for some specified string in multiple objects at the same time.
  • SOSL query begins with the required FIND clause.
  • The search string should be at least two characters long.
  • SOSL is used if we don’t know in which object the data is present.
  • We can mention in which fields of all the sObjects,we want to search for the string specified. Suppose you have to performed search on two objects Account & Contact. Then you can mention like, for list returned with Account results only (Name, Industry) fields should be returned, and for Contacts results (firstName, lastName) should be returned.
  • We can retrieve multiple objects and field values efficiently when the objects may or may not be related to each other.
  • We can query only on fields whose data type is text, phone and Email.
  • The result of SOSL is a list of lists of sObjects.
    The returned result contains the list of sObjects in the same order as order mentioned in SOSL query.
  • If a SOSL query does not return any records for a specified sObject type, then search results include an empty List for that sObject.
  • We can use SOSL in classes but not in Triggers.
  • We cannot perform DML operation on search result of SOSL.

Here in below example, there is a input text box and a command button which will search for the entered string in two Objects Accounts and Contacts and returned result will be shown in the page block tables.

Visualforce Page:

<apex:page controller="SampleController">
    <apex:form>
        <apex:inputText value="{!searchStr}"/>
        <apex:commandButton value="Get Records Using SOSL" action="{!Search}"/>
        <br/>
        <br/>
        <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:form>
</apex:page>

Apex Controller:

public class SampleController {
    Public List<Contact> conList {get; set;}
    Public List<Account> accList {get; set;}
    Public String searchStr {get; set;}
    
    Public void Search(){
        conList = New List<contact>();
        accList = New List<account>();
        List<List <sObject>> searchList = [FIND :searchStr IN ALL FIELDS RETURNING  Account (Id,Name,Type), Contact(Name,Email)];
        accList = ((List<account>)searchList[0]);
        conList  = ((List<contact>)searchList[1]);
    }
}

Output:

Test Class For Apex Trigger

Here in below example the apex trigger is on “Account” object, to check duplicate Account Names.

Apex Trigger:

trigger AccountTrigger on Account (before Insert, before Update) {
     
    Map<String, Account> accMap = new Map<String, Account>();
     
    for (Account acc : System.Trigger.new) {
         
        //Make sure you don't treat account Name that isn't changing during an update as a duplicate.  
        if (System.Trigger.isInsert || (acc.Name != System.Trigger.oldMap.get(acc.Id).Name)) {
             
            //Make sure another new account isn't also a duplicate  
            if (accMap.containsKey(acc.Name)) {
                acc.Name.addError('An account already exist with same name.');
            } else {
                accMap.put(acc.Name, acc);
            }
        }
    }
     
    //Query to find all the Accounts in the database that have the same name as any of the Accounts being inserted or updated.  
    for (Account acc : [SELECT Name FROM Account
                        WHERE Name IN :accMap.KeySet()]) {
                            Account newAcc = accMap.get(acc.Name);
                            newAcc.Name.addError('An account already exist with same name.');
                        }
}

Here is the Test Class for the above apex trigger.
Test Class:

@isTest
private class TestAccountTriggers {

    static testMethod void AccountTriggerUnitTest() {
	
        Account acc1 = new Account();
        acc1.Name = 'ABC Corp Ltd';
        acc1.Type = 'Prospect';
        acc1.Industry = 'Banking';
        Insert acc1;
		
        Account acc2 = new Account();
        acc2.Name = 'ABC Corp Ltd';
        acc2.Type = 'Prospect';
        acc2.Industry = 'Apparel';
		
        try
        {
        	Insert acc2;
        }
        catch(System.DMLException e)
        {
        	System.assert(e.getMessage().contains('An account already exist with same name.'));
        }
    }
}