Monday, December 5, 2016

Visualforce Page to Dynamically retrieve the Object and Its Fields.




Page:

<apex:page controller="GlobalDescibeDemoController">
    <apex:form id="Describe">
        <apex:pageBlock id="block2" >            
            <apex:pageblocksection >
                <apex:pageBlockSectionItem >
                    <apex:outputLabel >Object Name</apex:outputLabel>
                    <apex:selectList value="{!selectedObject}" size="1">
                        <apex:selectOptions value="{!ListObejectName}"/>
                    </apex:selectList>
                </apex:pageBlockSectionItem>
            </apex:pageblocksection>
            <apex:pageblockbuttons location="Bottom" >
                    <apex:commandButton value="Show Fields" action="{!showFields}" />
            </apex:pageblockbuttons>
        </apex:pageBlock>      
        <apex:pageBlock id="result" title="Field Detail for {!selectedObject}" rendered="{!if(listField.size > 0 ,true,false)}"   >
            <apex:pageBlockTable value="{!listField}" var="field" rendered="{!if(listField.size > 0 ,true,false)}">
                <apex:column value="{!field.fieldName }" headerValue="Name" />
                <apex:column value="{!field.fieldAPIName }"  headerValue="API Name"/>
            </apex:pageblockTable>
        </apex:pageblock>
    </apex:form>

</apex:page>

Controller:

public with sharing class GlobalDescibeDemoController {
    public Map <String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
    public String selectedObject {get; set;}
    public List<FieldWrapper> listField{get;set;}

    public GlobalDescibeDemoController () {
        listField = new List<FieldWrapper>();
    }

    // find all sObjects available in the organization
    public  List<SelectOption> getListObejectName()  {
        List<SelectOption> objNames = new List<SelectOption>();
        List<String> entities = new List<String>(schemaMap.keySet());
        entities.sort();
        for(String name : entities)
            objNames.add(new SelectOption(name,name));
        return objNames;
    }

   
    // Find the fields for the selected object
    public void showFields() {
        listField.clear();
        Map <String, Schema.SObjectField> fieldMap = schemaMap.get(selectedObject).getDescribe().fields.getMap();
        for(Schema.SObjectField sfield : fieldMap.Values())  {
            schema.describefieldresult dfield = sfield.getDescribe();
            FieldWrapper wObj = new FieldWrapper();
            wObj.fieldName = dfield.getLabel ();
            wObj.fieldAPIName = dfield.getname();
            listField.add(wObj);
        }
    }

    public class FieldWrapper {
        public String fieldName {get; set;}
        public String fieldAPIName {get; set;}
    }
}


No comments:

Post a Comment