Tuesday 12 April 2016

Dynamic Soql

Dynamic  SOQL  :
Based on the details enter in the above page dynamic query has to be formed
àIf no data is entered then query should  be
Select id,name,industy from Account
àIf user has entered only name  then the query should be
Select id,name ,industry from Account where name=nameentered
àIf the user has entered only industry query should be
Select id ,name,industry from Account where  industry=industryvalue entered
àIf  the use has entered name and industry query should be
Select id,name,Industry from Account where name=name and industry=industry;
Then execute the query and fetch the data and display in the pageblocktable

Apex Class :
public  class DynamicSoql {
     public String aindustry{Set;get;}
     public String aname{set;get;}
     public String query{set;get;}
     public List<Account> accs{set;get;}
     public void getData(){
          query='select id,name,phone,industry from Account';
          if((aname!='' && aname!= null)  && (aindustry!=null && aindustry!='')){
              query=query +' where name=\''+aname+'\' and industry=\''+aindustry+'\'';
          }
          else{
                   if(aname!=null && aname!=''){
                        query=query+' where name=\''+aname+'\'';
                   }
                   else if(aindustry!=null && aindustry!=''){
                        query=query+' where industry=\''+aindustry+'\'';
                   }
          }
          accs=Database.query(query);
     }

}
Ex:
<apex:page controller="DynamicSoql" >
<apex:form>
     <apex:pageBlock title="DynamicSoql">
          <apex:pageBlockSection>
              <apex:pageBlockSectionItem>
                   <apex:outputLabel value="Enter Name" />
                   <apex:inputText value="{!aname}" />
              </apex:pageBlockSectionItem>
              <apex:pageBlockSectionItem>
                   <apex:outputLabel value="Enter Industry" />
                   <apex:inputText value="{!aindustry}" />
              </apex:pageBlockSectionItem>
          </apex:pageBlockSection>
          <apex:commandButton value="Query" action="{!getData}" />

     </apex:pageBlock>
     <apex:pageBlock id="pb2" rendered="{! !ISNULL(accs)}">
     {!query}
          <apex:pageBlockTable value="{!accs}" var="a" >
              <apex:column value="{!a.name}" />
              <apex:column value="{!a.industry}" />
          </apex:pageBlockTable>
     </apex:pageBlock>
</apex:form>

</apex:page>

No comments:

Post a Comment