Create a dynamic SOQL Query using variable objects

15.2k views Asked by At

I'm trying to execute a dynamic soql query using variable objects. In my visualforce page i have tow apex:selectlist, the first one contains a list of objects, when i select one object from this list, i refresh the second list to display selected object's fields. The apex:inputText contains text to search in selected field.

visual force code:

<apex:selectList id="listObjects" value="{!selectedObject}" size="1">
    <apex:selectOptions value="{!allObjetcs}"></apex:selectOptions>
</apex:SelectList> 
<apex:selectList id="listFields" value="{!selectedField}" size="1">
    <apex:selectOptions value="{!allFields}"></apex:selectOptions>
</apex:SelectList> 
<label>Text to search : </label><apex:inputText id="textResearch" value="{!textResearch}" /> 
<button id="searchButton" type="button">{!$Label.SEARCH}</button> 

apex code :

public void search() {
        result = new List<SearchWrapper>();
        System.debug('>>>>>> ALK - in search ');
        String query = 'Select Id, ' + selectedField + ' from ' + selectedObject + ' where ' + selectedField + ' like \'%' + textResearch + '\'%';
        System.debug('>>>>>> ALK - Query : ' + query);
        List<sObject> = (sObject) Database.query(query);

}

Please how can i cast Database.query(query) and how can i execute this dynamic query.

Thanks for all.

3

There are 3 answers

0
Victor On

Try below code. If field list if multiselect, you might have to iterate over the selectedField variable and form a string of field names separated by comma.

String query = 'select '+String.valueOf(selectedField)+' From '+selectedObject+' WHERE Name = \'' + textResearch+'\'';
List<sObject> recordList = Database.query(query);
0
figosat On
public void search() {
    result = new List<SearchWrapper>();
    String query = 'Select ' + selectedField + ' from ' + selectedObject + ' where ' + selectedField + ' like \'%' + textResearch + '%\'';
    System.debug('>>>>>> Query : ' + query);
    List<sObject> l = Database.query(query);
}
0
Daniel On

if you are using a local variable in your query you must put ':' before that. like this:

String value = 'test';
List<something> result = [select id from something where name = :value];