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
Andrew EversleyAndrew Eversley 

Writing SOSL Queries - Trailhead Challenge Error

Apex Basics & Database Unit 5/5

Hello, Community, I am facing problem in solving this challenge, please advise.

Here is the criteria presented: 

With SOSL you can search against different object types that may have similar data, such as contacts and leads. To pass this challenge, create an Apex class that returns both contacts and leads that have first or last name matching the incoming parameter.

The Apex class must be called 'ContactAndLeadSearch' and be in the public scope.
The Apex class must have a public static method called 'searchContactsAndLeads'.
Because SOSL indexes data for searching, you must create a Contact record and Lead record before checking this challenge. Both records must have the last name 'Smith'. The challenge uses these records for the SOSL search.
The return type for 'searchContactsAndLeads' must be 'List<List< SObject>>'
The 'searchContactsAndLeads' method must accept an incoming string as a parameter, find any contact or lead that matches the string as part of either the first or last name and then return those records.

Error received: 

Challenge not yet complete... here's what's wrong: 
Executing the 'searchContactsAndLeads' method failed. Either the method does not exist, is not static, or does not return the expected search results.

Here is my code:

public class ContactAndLeadSearch{
    public static List<List< SObject>> searchContactsAndLead(String name)
    {
        List<List<sObject>> result=[FIND :name IN ALL FIELDS RETURNING Lead(LastName),Contact(LastName)];
                return result;
    }
}


PLEASE ADVISE...Thanks Community!!!
Best Answer chosen by Andrew Eversley
Amit Chaudhary 8Amit Chaudhary 8

Please try below class:-
Public Class ContactAndLeadSearch
{
        Public static List<List<sObject>> searchContactsAndLeads(String searchword)
        {
            String searchQuery = 'FIND \'' + searchword + '\' IN ALL FIELDS RETURNING Lead(Name,FirstName,LastName ), Contact(FirstName,LastName )';
            List<List<sObject>> searchConLead = search.query(searchQuery);
            return searchConLead;
        }
}

NOTE:- if you want to search same keyword in mutliple field then dnt add where you can try IN ALL FIELDS.

Execute below code in In Debug Annonymous window
 
List<List<sObject>> searchContactLead = ContactAndLeadSearch.searchContactsAndLeads('amit');

List<Lead> leadList = New List<Lead>();
List<Contact> contList = New List<Contact>();

leadList = ((List<Lead>)searchContactLead[0]);
contList = ((List<Contact>)searchContactLead[1]);

for(Lead a:leadList)
{
System.debug('Found following Leads ' + a.Name);
}
for(Contact cts:contList){
System.debug('Found following Contacts ' + cts.FirstName + '' + cts.LastName);
}
Please check below post
https://developer.salesforce.com/forums/?id=906F0000000BO5rIAG

Please let us know if this will help you

Thanks
Amit Chaudhary


 

All Answers

Amit Chaudhary 8Amit Chaudhary 8

Please try below class:-
Public Class ContactAndLeadSearch
{
        Public static List<List<sObject>> searchContactsAndLeads(String searchword)
        {
            String searchQuery = 'FIND \'' + searchword + '\' IN ALL FIELDS RETURNING Lead(Name,FirstName,LastName ), Contact(FirstName,LastName )';
            List<List<sObject>> searchConLead = search.query(searchQuery);
            return searchConLead;
        }
}

NOTE:- if you want to search same keyword in mutliple field then dnt add where you can try IN ALL FIELDS.

Execute below code in In Debug Annonymous window
 
List<List<sObject>> searchContactLead = ContactAndLeadSearch.searchContactsAndLeads('amit');

List<Lead> leadList = New List<Lead>();
List<Contact> contList = New List<Contact>();

leadList = ((List<Lead>)searchContactLead[0]);
contList = ((List<Contact>)searchContactLead[1]);

for(Lead a:leadList)
{
System.debug('Found following Leads ' + a.Name);
}
for(Contact cts:contList){
System.debug('Found following Contacts ' + cts.FirstName + '' + cts.LastName);
}
Please check below post
https://developer.salesforce.com/forums/?id=906F0000000BO5rIAG

Please let us know if this will help you

Thanks
Amit Chaudhary


 
This was selected as the best answer
Sandeep Mishra 7Sandeep Mishra 7
Hi Andrew,
I checked your code. That's perfect actually with little modifications:
public class ContactAndLeadSearch {
    public static List<List<SObject>> searchContactsAndLeads(String keyword)
    {
        list<list<sObject>> sobjects = [find :keyword IN ALL FIELDS Returning lead(FirstName, LastName), contact(firstname, lastname)];
        
        return sobjects;
    }
}
Also did you create few dummy data which were asked for? You can do this by going into Developer console and writing below code:
// Add account and related contact
Account acct = new Account(
    Name='Smith Computing',
    Phone='(415)555-1212',
    NumberOfEmployees=50,
    BillingCity='San Francisco');
insert acct;

// Once the account is inserted, the sObject will be 
// populated with an ID.
// Get this ID.
ID acctID = acct.ID;

// Add a contact to this account.
Contact con = new Contact(
    FirstName='Carol',
    LastName='Smith',
    Phone='(415)555-1212',
    Department='Wingo',
    AccountId=acctID);
insert con;

// Add account with no contact
Lead newLead = new Lead(
    FirstName='Tizen',
    LastName='Smith',
    Phone='(310)555-1213',
	Company='IGATE',
	LeadSource='Web');
insert newLead;


Just execute this. Try validationg your answers again. This should work.

Regards,
Sandeep Mishra
Andrew EversleyAndrew Eversley
@ Amit and @ Sandeep thanx for your posts and responses. Amit's response worked best for the challenge. Thank you both.
Yung WizardYung Wizard
I am getting the following error: The Lead and Contact records with the last name 'Smith' were not found. Please add these records for this challenge. Could someone please advise? I've pasted my code below. Thanks
 
public class ContactAndLeadSearch {
    
    public static List<List<SObject>> searchContactsAndLeads(string parameter) {
        
        Account acct = new Account (
        	Name = 'Smith Computing',
        	Phone = '(415 555-1212',
        	NumberOfEmployees = 50,
        	BillingCity = 'San Francisco');
        insert acct;
        ID acctID = acct.ID;
        
        Contact con = new Contact (
        	FirstName = 'Carol',
        	LastName = 'Smith',
        	Phone = '(415) 555-1212',
        	Department = 'Wingo',
        	AccountId = acctID);
        insert con;
        
        Lead theLead = new Lead(
        	FirstName = 'Jim',
        	LastName = 'Smith',
        	Phone = '(111) 111-1111',
        	Company = 'IGATE',
        	LeadSource = 'Web');
        insert theLead;
        
        List<List<SObject>> theList = [FIND: parameter IN ALL FIELDS RETURNING Contact(FirstName,LastName), Lead(FirstName, LastName)];
        
        return theList;
    }

}

 
Amit Chaudhary 8Amit Chaudhary 8
Hi
Please try to use below class,
NOTE:- You dnt need to create the Lead and contact record in Your Apex class. Please create the record in your salesforce org by TAB. Last Name should be Smith
Public Class ContactAndLeadSearch
{
        Public static List<List<sObject>> searchContactsAndLeads(String searchword)
        {
            String searchQuery = 'FIND \'' + searchword + '\' IN ALL FIELDS RETURNING Lead(Name,FirstName,LastName ), Contact(FirstName,LastName )';
            List<List<sObject>> searchConLead = search.query(searchQuery);
            return searchConLead;
        }
}

Please let us know if this will help you
Yung WizardYung Wizard
Thanks Amit - I was able to complete the challenge after creating the records in my salesforce org. 
Pawan Kumar BiradarPawan Kumar Biradar
Hi All.. can anyone please explain me the backslashes in the below string as m getting error without those slashes-
 
String searchQuery = 'FIND \'' + searchword + ' \' IN ALL FIELDS RETURNING Lead(Name,FirstName,LastName ), Contact(FirstName,LastName )'; 


can anyone please throw some light on those slashes. 

Thanks in advance.
Ravi Rao ArrabelliRavi Rao Arrabelli
Hi Pawan,
The backslashes are used as escape sequence to get single quote character, which is required in the SOSL query.
It will be read as FIND 'teststring' in ALL FIELDS.

Please refer, https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select_quotedstringescapes.htm for more information.
SenthilKumar mariappanSenthilKumar mariappan
Hi,
first of all you should have a contact, lead record with first or last name as Smith, then use the below code

public class ContactAndLeadSearch  { public static List<List<sObject>> searchContactsAndLeads(string input) { List<List<SObject>> searchList = [FIND :input IN ALL FIELDS                                        RETURNING Contact(FirstName,LastName), Lead(FirstName,LastName)]; return searchList; } }
Naveen DhanarajNaveen Dhanaraj
public class ContactAndLeadSearch {
    public static List<List<SObject>> searchContactsAndLeads(String sSearchParameter){
    List<List<sObject>> searchList = [FIND 'Smith' IN ALL FIELDS RETURNING Contact(lastName), Lead(LastName) ];
    Contact[] searchContacts = (Contact[])searchList[0];
    Lead[]    searchLeads =    (Lead[])searchList[1];
System.debug('Found the following contacts.');
for (Contact c : searchContacts) {
    System.debug(c.LastName );
}
System.debug('Found the following Leads.');
for (Lead l : searchLeads) {
    System.debug(l.LastName );
}
    return searchList;
}
}
Vladimir Mir 1Vladimir Mir 1

Hi Guys, thought I would throw in my two pence about reading instructions carefully. It says:  Find "contacts and leads that have first or last name matching the incoming parameter." Hence IN NAME FIELDS should be used instead of IN ALL FIELDS.

I bet you will have passed the test anyway, but this would make the solution completely flawless.

[FIND :keyword IN NAME FIELDS
                       RETURNING Contact(FirstName,LastName),Lead(FirstName,LastName)];
Charisse de BelenCharisse de Belen
Hi all, just piggybacking off this question.

My class looks like this:
public class ContactAndLeadSearch {
    public static List<List<SObject>> searchContactsAndLeads(String search) {
        List<List<SObject>> searchList = [FIND :search IN NAME FIELDS
                                          RETURNING Contact(FirstName, LastName),
                                                       Lead(FirstName, LastName)];
        
        return searchList;
    }
}

I modified one of my leads so that neither the first name nor the last name is Smith, but I included "Smith" in the company name. When I test this code, that lead is included in the result. My code passes the challenge so I guess that's not a problem, but I want to know if there's a way to write the query so that this lead is not included in the result, since the challenge technically asks for leads and contacts with only first name or last name of Smith.
rizwan ahmed 16rizwan ahmed 16

public class ContactAndLeadSearch{

public static list<list<SObject>> searchContactsAndLeads(String LastName)
        {

            List<List<SObject>> searchList = [FIND 'Smith' IN ALL FIELDS RETURNING Lead (LastName), Contact(LastName)];
            return searchList;
          }


}
pablotmpablotm

For the people that is getting the error:
"The Lead and Contact records with the last name 'Smith' were not found. Please add these records for this challenge." 

You can solve it by just adding a contact and/or a lead with the last name 'Smith' to your org (playground) . 
I had already 2 contacts, but no leads in the org with last name 'Smith'.

Execute this in an Anonymous Windows:

//For adding the Lead
Lead newLead = new Lead(
    FirstName='Tizen',
    LastName='Smith',
    Phone='(310)555-1213',
    Company='IGATE',
    LeadSource='Web');
insert newLead;

//For adding the Contact
Contact con = new Contact (
    FirstName = 'Carol',
    LastName = 'Smith',
    Phone = '(415) 555-1212',
    Department = 'Wingo',
    AccountId = acctID);
insert con;

 
Amit Kumar 447Amit Kumar 447
Hi ALl,

Can someone please paste the code for Developer Console Anonymous window to execute below code. As i am getting error: Line: 2, Column: 9
Static method cannot be referenced from a non static context: List<List<SObject>> ContactAndLeadSearch.searchContactsAndLeads(String)

Code: 

public class ContactAndLeadSearch {
    public static List<List<SObject>> searchContactsAndLeads(string parameter) {
         
        Account acct = new Account (
            Name = 'Smith Computing',
            Phone = '(415 555-1212',

            NumberOfEmployees = 50,

            BillingCity = 'San Francisco');
        insert acct;
        ID acctID = acct.ID;
      
       Contact con = new Contact (
            FirstName = 'Carol',
            LastName = 'Smith',
            Phone = '(415) 555-1212',
            Department = 'Wingo',
            AccountId = acctID);
        insert con;
        
        Lead theLead = new Lead(
            FirstName = 'Jim',
            LastName = 'Smith',
            Phone = '(111) 111-1111',
            Company = 'IGATE',

            LeadSource = 'Web');
        insert theLead;
        
        List<List<SObject>> theList = [FIND: parameter IN ALL FIELDS RETURNING Contact(FirstName,LastName), Lead(FirstName, LastName)];
         
        return theList;
    }
}
 
Mr PolskiMr Polski
Hi Amit ,
Please run below code in execute anonymous block :
ContactAndLeadSearch.searchContactsAndLeads('smith');

Thank you ,
Tawseef
Edward BruntonEdward Brunton
Make sure to excute the following anoymously before trying:
        Account acct = new Account (
            Name = 'Smith Computing',
            Phone = '(415 555-1212',

            NumberOfEmployees = 50,

            BillingCity = 'San Francisco');
        insert acct;
        ID acctID = acct.ID;
      
       Contact con = new Contact (
            FirstName = 'Carol',
            LastName = 'Smith',
            Phone = '(415) 555-1212',
            Department = 'Wingo',
            AccountId = acctID);
        insert con;
        
        Lead theLead = new Lead(
            FirstName = 'Jim',
            LastName = 'Smith',
            Phone = '(111) 111-1111',
            Company = 'IGATE',

            LeadSource = 'Web');
        insert theLead;


 
Yogesh PrajapatiYogesh Prajapati
Since we just need to find it in Name Fields and return the Contact and Lead Object.
Here is my simple solution


public class ContactAndLeadSearch {
public static List<List<SObject>> searchContactsAndLeads(String keyword)
{
    List<List<sObject>> searchList = [FIND :keyword IN NAME FIELDS RETURNING Contact , Lead];
    return searchList;
}
}
Swapnagandha HawaldarSwapnagandha Hawaldar
I struggled with this problem as well. Here is what you can do:

1. In your Execute Anonymous window, use System.debug statements to print Contact and Lead objects from your List<List<SObject>> result.
2. If it is returning correct result i.e. at least one Lead and one Contact with their last names Smith, then the problem is with data.
3. Start with a clean trailhead playground, add one Lead and one Contact with their last names Smith. And then run your script

Worked for me.
kets starskets stars

here is code details

 

public class ContactAndLeadSearch {

    public static List<List<SObject>> searchContactsAndLeads(string strstring)
    {
        List<List<SObject>> searchList = [FIND :strstring IN ALL FIELDS RETURNING Lead(Name),Contact(FirstName,LastName,Department)];
        Lead[] searchLead = (Lead[])searchList[0];
        Contact[] searchContacts = (Contact[])searchList[1];
        
        System.debug('Found the following Leads.');
        for (Lead L : searchLead) {
            System.debug('=== LEAD Name==' + L.Name);
        }

        System.debug('Found the following contacts.');
        
        for (Contact c : searchContacts) {
        System.debug('Last Name == > ' +c.LastName + ', First Name==>' + c.FirstName);
        }
       
       return searchList;
    }

 
}

RAJDEEP CHAKRAVARTYRAJDEEP CHAKRAVARTY
Hi Andrew Eversley,
Your logic and code was perfectly fine
the only place it showled error was the method name "searchContactsAndLeads"  where as your was "searchContactsAndLead"
the 's' was missing from Leads.
Thank you,
Rajdeep
Vivek Yadav 55Vivek Yadav 55
@Charisse de Belen I have the same doubt as you do...pls do let me know if you find the solution
Ntrial user 9Ntrial user 9
public class ContactAndLeadSearch {
    Public static List<List<sObject>> searchContactsAndLeads(string CLName){
    
        List<List<sObject>> searchlist = [Find :CLNAME IN ALL FIELDS 
                                         RETURNING Contact(FirstName,LastName),Lead(FirstName,LastName)];
        Contact[] searchContacts = (Contact[])searchList[0];
        Lead[] searchLeads = (Lead[])searchList[1];
        for(contact c1 : searchContacts){
            system.debug('The contact with the name'+c1.FirstName+','+c1.LastName);
            
        }
        for(Lead L : searchLeads){
            system.debug('The Lead with the name'+L.FirstName+','+L.LastName);
            

}
        return searchList;
}
}
Saquib MansuriSaquib Mansuri
Follow these steps , it will surely work
-Open developer console>debug>Open execute anonymous window
-Paste this code to create sample data of contact and lead

Account acct = new Account(
    Name='Smith Computing',
    Phone='(415)555-1212',
    NumberOfEmployees=50,
    BillingCity='San Francisco');
insert acct;

// Once the account is inserted, the sObject will be 
// populated with an ID.
// Get this ID.
ID acctID = acct.ID;

// Add a contact to this account.
Contact con = new Contact(
    FirstName='Carol',
    LastName='Smith',
    Phone='(415)555-1212',
    Department='Wingo',
    AccountId=acctID);
insert con;

// Add account with no contact
Lead newLead = new Lead(
    FirstName='Tizen',
    LastName='Smith',
    Phone='(310)555-1213',
    Company='IGATE',
    LeadSource='Web');
insert newLead;

-CLICK ON EXECUTE


-- Now create a class named ContactAndLeadSearch and paste the following code (YOUR END RESULT SHOULD LOOK LIKE THIS)

public class ContactAndLeadSearch {
    public static List<List<sObject>> searchContactsAndLeads(String x){
        List<List<SObject>> searchList = [FIND :x IN ALL FIELDS RETURNING contact(firstName,lastname), lead(firstname,lastname)];
        return searchlist;
    }

}


--Check your answer
Thank You

 
Ram NepRam Nep
The following code worked for me:

Public Class ContactAndLeadSearch
{
        Public static List<List<sObject>> searchContactsAndLeads(String searchword)
        {
            String searchQuery = 'FIND \'' + searchword + '\' IN ALL FIELDS RETURNING Lead(Name,FirstName,LastName ), Contact(FirstName,LastName )';
            List<List<sObject>> searchConLead = search.query(searchQuery);
            return searchConLead;
        }
}

Note: Also make sure that you have created contact and lead records each with the last name 'Smith'.
Neil FNeil F
Hello all, 

I've used the code below to complete the challenge, and this code is similar to that of these posts, but I do not think the code meets this requirement of the challenge: 

The method should then find any contact or lead that matches the string as part of either the first or last name

public class ContactAndLeadSearch {
    public static List<List< sObject>> searchContactsAndLeads(string searchstring) {
        List<List<sObject>> searchList = [FIND :searchstring IN ALL FIELDS
                                         RETURNING lead(FirstName, LastName, company), 
                                          contact(firstname, lastname)]; 
        system.debug(searchList); 
      return searchList; 
    }
}

22:25:33:160 USER_DEBUG [6]|DEBUG|((Lead:{FirstName=TestLead, LastName=Smith, Company=ABCCo, Id=00Q8c000017dssgEAA}, Lead:{FirstName=TestLead, LastName=Ramsey, Company=Smith, Id=00Q8c000017dszIEAQ}), (Contact:{FirstName=TestContact, LastName=Smith, Id=0038c00003FSLomAAH}))

This code returns an entry where the search string "Smith" is the company name. Can anyone help in meeting the requirement that the search parameter is only applied to the first or last name? Thank you very much. 
André HenriqueAndré Henrique

I used the following code and it worked.

 

public class ContactAndLeadSearch {
    public static List<List<sObject>> searchContactsAndLeads(String searchName) {
        String searchString = '%' + searchName + '%';
        List<List<sObject>> searchResults = [
            FIND :searchString IN NAME FIELDS RETURNING Contact(FirstName, LastName), Lead(FirstName, LastName)
        ];
        
        return searchResults;
    }
}
 

Neil FNeil F
Thank you for the response, Andre. I'm still getting a record returned with Smith in the company name (and not in the name fields) with that code. I'll troubleshoot a bit and/or open a new question on the same. Not sure why this is happening. 

09:10:45:162 USER_DEBUG [7]|DEBUG|%smith%
09:01:05:102 USER_DEBUG [7]|DEBUG|((Contact:{FirstName=TestContact, LastName=Smith, Id=0038c00003FSLomAAH}), (Lead:{FirstName=TestLead, LastName=Ramsey, Id=00Q8c000017dszIEAQ}, Lead:{FirstName=TestLead, LastName=Smith, Id=00Q8c000017dssgEAA}))