Thursday, 4 August 2016

How to create Dynamic SOQL in salesforce

Dynamic SOQL means creation of  query at run-time using apex and get records after executing that query in your code. We can create dynamic query with the help of apex code easily.

Here is an example in which I will show you how to create a Dynamic Query with apex code:



Apex Code:

public class DynamicApex 
{
    public map<String,Schema.SobjectType> ofmap=Schema.getGlobalDescribe();
    public string selectedObject{get;set;}
    public list<string> selectedfield{get;set;}
    public string temp{get;set;}
    public string temp1{get;set;}
    public list<sobject> q{get;set;}
    
    public DynamicApex ()
    {
        selectedObject='none';
        q=new list<sobject>();
        selectedfield=new list<string>();
    }
    
    public List<selectoption> getobject()
    {
        list<selectoption> objectname=new list<selectoption>();
        list<string> mapkey=new list<string>(ofmap.keyset());
        objectname.add(new selectoption('None','None'));
        mapkey.sort();
        for(String s:mapkey)
        {
            objectname.add(new selectoption(s,s));
        }
        return objectname; 
    }
    
    public List<selectoption> getfields()
    {
        list<selectoption> field=new list<selectoption>();
        if(selectedObject!='none')
        {
            schema.sobjectType objtype=ofmap.get(selectedobject);
            map<String,Schema.sobjectField> fieldmap=objtype.getDescribe().fields.getmap();
            for(String F:Fieldmap.KeySet())
            {
                field.add(new selectoption(F,F));
            }
        }
        return field;
    }
    
    public void Soql()
    {       
          temp='select ';
          for(String field:Selectedfield)
          {
              if(Field!=Selectedfield.get(Selectedfield.size()-1))
              {
                  temp+= field+','+' ';
              }
              else
              {
                  temp+= field+' ';
              }
          }
          
          temp+='from '+ SelectedObject;
          q= Database.query(temp) ;
    }
}

Visualforce page Code:

<apex:page controller="DynamicApex">
<apex:form >
<apex:pageblock >
    
    <apex:pageblockButtons location="Top">
    <apex:commandButton value="Click" action="{!soql}"/>
    </apex:pageblockButtons>

    <apex:pageblockSection columns="4">
   
    <apex:pageblocksectionItem >
        <apex:outputLabel value="Object:"/>
            <apex:selectList value="{!selectedobject}" size="1">
                <apex:selectOptions value="{!object}"/>
                    <apex:actionSupport event="onchange" reRender="myfields"/>
            </apex:selectList>
      </apex:pageblocksectionItem>
     
     <apex:pageblocksectionItem >
         <apex:outputLabel value="Fields:"/>
            <apex:outputPanel id="myfields">
                <apex:selectList value="{!selectedField}" multiselect="true" size="5">
                    <apex:selectOptions value="{!fields}"/>
                </apex:selectList>
            </apex:outputPanel>
        </apex:pageblocksectionItem>
       
        <apex:outputLabel value="Dynamic Query:"/>
        <apex:inputtextarea rows="5" cols="50" value="{!temp}" />
    </apex:pageblockSection>
    
        <apex:pageblockTable value="{!q}" var="t" >
            <apex:repeat value="{!selectedField}" var="sf">
                <apex:column value="{!t[sf]}"/>
            </apex:repeat>
        </apex:pageblockTable>
        
        <apex:outputPanel rendered="{!IF(q.size < 1 , true , false)}">
           <apex:pageMessage severity="ERROR" summary="No records to display"/>
        </apex:outputPanel>
        

</apex:pageblock>
</apex:form>
</apex:page>

In this example after click on button you can create dynamic query and get the records in table of that query as shown above in the image.


No comments:

Post a Comment