Dynamic object handling

<apex:page controller="dynObjHandling">
    <apex:form >
        <apex:selectList label="Obj" size="1" value="{!MetadataType}" >
            <apex:selectOptions value="{!MetadataTypes}"/>
            <apex:actionSupport event="onchange"  action="{!createNewSobj}" reRender="op1" status="status"/> <apex:actionStatus id="status" startText="Please ...."></apex:actionStatus>
        </apex:selectList>
        <apex:outputPanel id="op1">
        {!MetadataType}
            <apex:outputPanel rendered="{!IF(dynObj != null, true, false)}">
                    <apex:pageBlock >
        <apex:pageBlockSection >
                <apex:repeat value="{!fields}" var="f">
                    <apex:inputField value="{!dynObj[f]}"/>
                </apex:repeat>
        </apex:pageBlockSection>
        </apex:pageBlock>
            </apex:outputPanel>
            <apex:commandButton action="{!doSave}" value="Save"/>
        </apex:outputPanel>
    </apex:form>
</apex:page>


public class dynObjHandling {

    public PageReference doSave() {
        insert dynObj;
        return (new pagereference('/'+dynObj.Id).setredirect(true));
    }


    public sObject dynObj {get;set;}
    public Map <String, Schema.SObjectField> fieldMap {get;set;}
    public PageReference createNewSobj() {
            dynObj = gdMap.get(MetadataType).newSObject();
            fieldMap = gdMap.get(MetadataType).getDescribe().fields.getMap();
            fields = new List<String>();
            for (String fieldName: fieldMap.keySet()) { 
                if(fieldMap.get(fieldName).getDescribe().isUpdateable())
                fields.add(fieldName);
            }
        return null;
    }


    public Map <String, Schema.SObjectType> gdMap = Schema.getGlobalDescribe();
    public List<SelectOption> MetaDataTypes {get; set;}
    public List<String> fields {get;set;}
    public String MetadataType { get; set; }    
    public dynObjHandling(){
        MetaDataTypes = new List<SelectOption>();  
        fields = new List<String>();
        MetaDataTypes.add(new SelectOption('--Select--', '--Select--'));
        for(Schema.SObjectType f : gdMap.Values())
        {    
            if(f.getDescribe().isAccessible())
            MetaDataTypes.add(new SelectOption(f.getDescribe().getName(), f.getDescribe().getLabel()));
        }
        MetadataTypes.sort();
    }
}




Dynamically getting sObject Name 
sObject a = [Select Id, Name FROM Account LIMIT 1];
system.debug(a.getSObjectType().getDescribe().getName());


Comments

Popular Posts