I have this below method which i want to make it more generic which can be used for any object and pass any filter to SOSL query according to object passed(build dynamic) . From lightning component i will be passing object name. How to do it.
How can i use a dynamic variable after RETURNING word to pass any Object
@AuraEnabled(Cacheable=true)
public static List<LookupSearchResult> searchCountries(String searchTerm, List<String> selectedIds, String objectName) {
system.debug('searchTerm' + searchTerm);
// Prepare query paramters
searchTerm += '*';
// Execute search query
List<List<SObject>> searchResults = [FIND :searchTerm IN ALL FIELDS RETURNING
Test__c (Id, Name WHERE Name NOT IN :selectedIds)
LIMIT :MAX_RESULTS];
system.debug('searchResults' + searchResults);
// Prepare results
List<LookupSearchResult> results = new List<LookupSearchResult>();
String geoIcon = 'custom:custom9';
Test__c [] tst = ((List<Test__c >) searchResults[0]);
for (Test__c t: tst) {
results.add(new LookupSearchResult(t.Id, 'Test__c', geoIcon, t.Name, 'Test • '));
}
return results;
}
LookupSearchResult.cls
public class LookupSearchResult {
private Id id;
private String sObjectType;
private String icon;
private String title;
private String subtitle;
public LookupSearchResult(Id id, String sObjectType, String icon, String title, String subtitle) {
this.id = id;
this.sObjectType = sObjectType;
this.icon = icon;
this.title = title;
this.subtitle = subtitle;
}
}
Best Answer
You can use this method. This can be used for both SOQL or SOSL.
Parameter
params
is a generic way of passing the data from client-side to apex method - can add/remove any part of data for scalability.fields - comma separated fields (can have relation-ship fields too)
objectName - api name of object from where you need to query
Find below the method:
IMPORTANT: