Salesforce | Dynamic object name in SOQL query

|
| By Webner

Problem:

We have a visualforce page with a drop down list (apex:selectlist) containing Salesforce object names and a corresponding input box (apex:inputText). Requirement is to select an object from dropdown, enter a value in the input box and on submit search records of selected object that contain input box value in a particular field.

For example, in this query:

List result = [select Id, Name, FirstName, LastName from Contact where LastName = :searchString];

We are searching in Salesforce Contact object in which LastName contains ‘searchString’.

But in our case we do not know if we have to search in Contact, Product, Invoice, Quote or any other object.

So our query has to be something like this:

select Id, Name, FirstName, LastName from ‘selectedObject’ where LastName = ‘searchString’

Solution:

For providing the object name to SOQL dynamically we retrieved the selected dropdown value into ‘selectedObject’ variable and the string to be searched in ‘searchString’. Then we created the query string that needs to be passed to Database.query() for execution as below:

String query = 'select Id, Name, FirstName, LastName From '+selectedObject+' WHERE LastName = '' + ‘searchString’+''';
List records = Database.query(query);

For the type of results to be returned by query we need to use sObject that will map return values to the specific object that is queried.

Webner Solutions is a Software Development company focused on developing CRM apps (Salesforce, Zoho), LMS Apps (Moodle/Totara), Websites and Mobile apps. If you need Salesforce customization, App development or any other software development assistance please contact us at salesforce@webners.com

Leave a Reply

Your email address will not be published. Required fields are marked *