I have a Lightning component with a search bar that uses Apex to search Cases, and another that searches Opportunities. For example:
@AuraEnabled
public static List<Case> searchCases(String searchKey)
{
String name = '%' + searchKey + '%';
if(!Case.SObjectType.getDescribe().isAccessible()){
return null;
}else
{
return
[
SELECT Account.Name,Subject,Status,CreatedDate, Contact.Name, Priority
FROM Case
WHERE Subject LIKE :name OR Account.Name LIKE :name
ORDER BY LastViewedDate DESC
];
}
}
Now, I want to provide search integration with custom objects, which the admin will be able to specify from a pulldown menu when they drop the component on the page in page builder. I built a class to create the list of custom objects, and I've wired that into the .design file of the component. So now, my search bar component will be able to access the name of the custom object -- let's say Applicants__c
, for example.
Now, I'm creating a the search bar functionality where I'll be searching the Name field of the custom object. I'll call the apex method, providing the searchKey and the name of the custom object. I need help figuring out how to use that dynamic custom object name to check for accessibility, and to execute the search. So the first part...
I tried this:
@AuraEnabled
public static List<Object> searchRecords(String searchKey, String custObj)
{
String name = '%' + searchKey + '%';
if(!custObj.SObjectType.getDescribe().isAccessible()){
return null;
}else ...
And got this error:
Variable does not exist: SObjectType
I also tried specifying the incoming param as an SObject and an SObjectType, with no luck. Same error when I try to push to scratch org.
The docs say you can't bind the FROM aspect of a SOQL search, so I figure I'll build the string dynamically. Here's my best shot, which is compiling ok.
@AuraEnabled
public static List<Object> searchRecords(String searchKey, String custObj)
{
String name = '%' + searchKey + '%';
if(!custObj.SObjectType.getDescribe().isAccessible()){
return null;
}else
{
String searchQuery = 'FIND :name IN NAME FIELDS RETURNING :' + custObj + '(Name,LastModifiedDate)';
return search.query(searchQuery);
}
}
Any tips welcome. Thanks.