Salesforce: Dynamic SOQL Chapter 3
Salesforce: Dynamic SOQL Chapter 3
So in the previous post, we have learned how to get all sObjects and its related field in the runtime. Feel free to play around with the describe calls and describe result classes, next we are going to learn how to make a dynamic SOQL and display the result of the same on a Visualforce page.
To make a dynamic SOQL we need a sObject, its field and that too in a proper format. We know that to use “[select … From object]”, we need to beforehand what is the type of sObject, because it returns a list of specific sObjectType. To overcome this we use another method of Database class i.e. “Database.query();”.
public class PostTestingClass {
public list<selectoption> fieldList {
get{return findTheFields();}
set;}
public string selectedObject = ‘account’;
public Map <String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe(); // Org Map
public string queryString {
get{
string finalQueryString = ‘select ‘ ;
for(SelectOption s:fieldList){
finalQueryString = finalQueryString + s.getValue() + ‘,’;
}
finalQueryString = finalQueryString.removeEnd(‘,’);
finalQueryString += ‘ from ‘ + selectedObject;
return finalQueryString ;}
set;
}
public list<selectoption> findTheFields(){
list<selectoption> fieldList1 = new list<selectoption>();
Map<String, Schema.SObjectField> schemaFieldMap = schemaMap.get(selectedObject).getDescribe().fields.getMap();
for(Schema.SObjectField sfield : schemaFieldMap.Values()){
schema.describefieldresult dfield = sfield.getDescribe();
fieldList1.add(new SelectOption(dfield.getname(),dfield.getlabel()));
}
return fieldList1;
}
}
In the code above we take the value of sObject dynamically, then we find the related fields of the objects and then using the values we make query string according to the syntax of SOQL. Now we can use this query to fetch the list of sObjects using the database.query() method.
Visualforce page: –
<apex:page controller=”PostTestingClass” >
<apex:form>
<apex:pageBlock>
<apex:selectList size=”1″>
<apex:selectOptions value=”{!fieldList}”></apex:selectOptions>
</apex:selectList><br/><br/><br/>
<apex:inputTextarea value=”{!queryString}” />
</apex:pageBlock>
</apex:form>
</apex:page>
[…] fieldList; set; Salesforce: Dynamic SOQL Chapter 3 | SalesforceNextGen. Salesforce: Dynamic SOQL Chapter 3 So in the previous post, we have learned how to get all […]
[…] Sourced through Scoop.it from: salesforcenextgen.com […]
[…] Salesforce: Dynamic SOQL Chapter 3 […]