How to retrieve fields based on selected object by Dynamic Apex?

How to retrieve fields based on selected object by Dynamic Apex?

Sample Code:


Visualforce page:

<apex:page controller=”Sample” >
<apex:form >
    <apex:pageBlock >
        <apex:pageBlockSection >
            <apex:pageBlockSectionItem >
                <apex:outputLabel value=”Objects”/>
            </apex:pageBlockSectionItem>       
            <apex:pageBlockSectionItem >
                <apex:selectList size=”1″ value=”{!obj}” >
                    <apex:selectOptions value=”{!objs}”/>
                </apex:selectList>
            </apex:pageBlockSectionItem>                     
        </apex:pageBlockSection>
        <apex:pageblockButtons >
            <apex:commandButton value=”Fetch Fields” action=”{!fetchFields}” reRender=”flds”/>
        </apex:pageblockButtons>
    </apex:pageBlock>
    <apex:pageblock id=”flds” title=”Fields”>
        <apex:pageblockTable value=”{!objFields}” var=”f”>
            <apex:column value=”{!f}” />
        </apex:pageblockTable>
    </apex:pageblock>   
</apex:form>   
</apex:page>



Apex controller:

public class Sample
{
    public String obj;
    public List<String> objFields {get;set;}
   
    public Sample()
    {   
    }
   
    public String getobj()
    {
        return obj;
    }
   
    public void setobj(String obj)
    {
        this.obj = obj;
    }  
   
    public List<SelectOption> getobjs()
    {
        List<Schema.SObjectType> gd = Schema.getGlobalDescribe().Values();   
        List<SelectOption> options = new List<SelectOption>();
              
        for(Schema.SObjectType f : gd)
        {
            options.add(new SelectOption(f.getDescribe().getName(),f.getDescribe().getName()));
        }
        return options;
    }
 
    public void fetchFields()
    {
        List<String> fields = new List<String>();
        Map<String , Schema.SObjectType> globalDescription = Schema.getGlobalDescribe();
        System.debug(‘Selected Object is ‘ + obj);
        Schema.sObjectType objType = globalDescription.get(obj);
        System.debug(‘Object Type is ‘ + objType);
        Schema.DescribeSObjectResult r1 = objType.getDescribe();
       
        Map<String , Schema.SObjectField> mapFieldList = r1.fields.getMap(); 

        for(Schema.SObjectField field : mapFieldList.values()) 
        { 
            Schema.DescribeFieldResult fieldResult = field.getDescribe(); 
           
            if(fieldResult.isAccessible()) 
            { 
                System.debug(‘Field Name is ‘ + fieldResult.getName());
                fields.add(fieldResult.getName());
            } 
        }
        List<String> so = new List<String>();
        for(String f : fields)
        {
            so.add(f);
        }
        objFields = so;      
    }  
}




Output:

Leave a Reply