Search names with SOSL
Query the org (SOQL) · Intermediate · 18 min · Runs in your Salesforce Developer org · Apex Path
Scenario. A support rep types part of a name into one search box. They expect matching companies first, then matching people, each in A to Z order.
Run one SOSL search across Accounts and Contacts, return the names in a set order, and see why tests need Test.setFixedSearchResults.
What you will learn
SOSL searches for text in several objects at once. It gives back one list per object, in the order you name them after RETURNING.
List<List<SObject>> hits = [
FIND :term IN NAME FIELDS
RETURNING Account(Name), Contact(LastName)
];
Gotcha. SOSL looks in a search index, which Salesforce updates shortly after each save, so a record you just saved may not show up yet. In a test, SOSL finds nothing until you call Test.setFixedSearchResults(ids).
The task
Complete findNames so one SOSL search returns the names of matching Accounts, then the last names of matching Contacts.
Examples:
findNames('Harbor')finds AccountsHarbor BetaandHarbor Alphaand a Contact named Maya Harbor →(Harbor Alpha, Harbor Beta, Harbor)findNames('Nobody')finds nothing → an empty listfindNames(null),findNames(' ')orfindNames(' H ')→ an empty list, and no search runs
Requirements:
- SOSL needs at least 2 characters. If
termis null, blank, or shorter than 2 characters after you trim the spaces, return an empty list (not null) without searching. - Run one SOSL search for the trimmed term
IN NAME FIELDS, returning AccountNameand ContactLastName. - Sort each object A to Z with
ORDER BYinside its part ofRETURNING. - Add every Account
Namefirst, then every ContactLastName, and return the list.
Starter code
public class AS_6C2F11FEB11B_NameSearch {
public static List<String> findNames(String term) {
List<String> names = new List<String>();
return names;
}
}
When it passes
One SOSL search returns Account names A to Z, then Contact last names A to Z. A missing, blank or 1-character term returns an empty list without searching, and a search with no hits returns an empty list.
You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.