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
rushi ettam 7rushi ettam 7 

passing string parameter to sosl searchQuery

in Apex Basics&Database SOSL Queries
We have challenge to pass the string parameter as input and depend upon that string made sosl query
but in reality how can you make that
searchQuery in SOSL accept text search
syntax as find 'smith' in all fields

So the question is how can we put the variable name in place of string???
Best Answer chosen by rushi ettam 7
Jithin Krishnan 2Jithin Krishnan 2

Hi Rushi,
You need to construct a query string with your search string like below and use search.query(searchQuery):
String searchQuery = 'FIND \'' + searchstring + '\' IN ALL FIELDS RETURNING Account (id, name, address), Contact, Lead'; 
List<List<sObject>> searchList = search.query(searchQuery);

Where searchstring is the string you want to search.
Thanks

All Answers

Jithin Krishnan 2Jithin Krishnan 2

Hi Rushi,
You need to construct a query string with your search string like below and use search.query(searchQuery):
String searchQuery = 'FIND \'' + searchstring + '\' IN ALL FIELDS RETURNING Account (id, name, address), Contact, Lead'; 
List<List<sObject>> searchList = search.query(searchQuery);

Where searchstring is the string you want to search.
Thanks
This was selected as the best answer
Kyle NovelliKyle Novelli
Hey Rushi and Jithin,

I know this is a bit old, but you can also access a String variable within a SOSL query using a colon before the String variable.

For example,

    public static List <List <SObject> > searchContactsAndLeads(String str) {
        List <List<SObject>> searchList = [FIND :str IN ALL FIELDS RETURNING Contact(FirstName,LastName),Lead(FirstName,LastName)];
        return searchList;
    }
Jeevanprakash C MJeevanprakash C M
Thanks Kyle Novelli.  That works and easy solution
Tamoghna Dey 5Tamoghna Dey 5
public class ContactAndLeadSearch {

    Public static List<List<SObject>> searchContactsAndLeads(String Param){
        List<List<SObject>> searchList=[FIND :Param IN ALL FIELDS RETURNING Contact(FirstName, LastName), Lead(LastName, Company)];
        return searchList;
    }
}
Aabid AnsarAabid Ansar
public class ContactAndLeadSearch {
public static List<List<sObject>> searchContactsAndLeads(String a)
{
    List<List<sObject>> searchList = [FIND :a IN ALL FIELDS RETURNING Contact(FirstName,LastName) , Lead(FirstName,LastName)];
    return searchList;
}
}