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.
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.