Sunday, 30 December 2012

Dynamic Query and Dynamic class-(12/31/12)


Here we have a scenario -->Create a Textbox(object name) and search button: 
if the value entered in textbox is equal to object name then display that object records
    in a Pageblocktabke below it  else display error.


VF Page:-

<apex:page controller="practice4">
    <apex:form >
        <apex:pageBlock >
            <apex:pagemessages ></apex:pagemessages>
               
            <apex:pageBlockSection title="Object Name">
                <apex:pageBlockSectionItem >
                    <apex:outputLabel value="Enter Object Name"/>
                    <apex:inputText value="{!objname}"/>
                </apex:pageBlockSectionItem>
                <apex:commandButton value="Search" action="{!search}"/>
            </apex:pageBlockSection>
            <apex:pageBlockSection title="List of Records" rendered="{!show}">
                <apex:pageBlockTable value="{!innervar}" var="a">
                    <apex:column headerValue="Record ID" value="{!a.str1}"/>
                    <apex:column headerValue="Record Name" value="{!a.str2}"/>
                </apex:pageBlockTable>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Apex Class:-
------

public class practice4 {
    public String objname { get; set; }
    public List<myclass> innervar{get;set;}
    public boolean show{get;set;}
    public practice4 (){
        show=true;
        innervar=new List<myclass>();
    }
    public class myclass{
        public Id str1{get;set;}
        public String str2{get;set;}
        public myclass(ID id,String name){
            str1=id;
            str2=name;
        }
    }
    public void search() {
        try{
            Schema.SObjectType t  = Schema.getGlobalDescribe().get(objname);
            if(t!=null){
                show=true;
                String SOQL = 'SELECT id,Name FROM ' + t;
                for (List<SObject> sobjs : Database.query(SOQL)) {
                    for (SObject sobj : sobjs) {
                        innervar.add(new myclass(sobj.id,String.valueOf(sobj.get('name'))));
                    }
                }
            }
            else{
                show=false;
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error,' Please Enter Existing Object Name!'));
            }
        }
        catch(Exception e){
        }
    }
}



No comments:

Post a Comment