Friday, March 9, 2012

Inserting sObject Dynamically in Salesforce

How I can insert sObject record dynamically?
Visualforce Page code :
<apex:page controller="InsertDynamicSobjectController">
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockButtons >
                <apex:commandButton value="Save" action="{!Save}"/>
            </apex:pageBlockButtons>
            <apex:pageMessages />
            <apex:pageBlockSection >
                <apex:pageBlockSectionItem >
                    <apex:outputLabel value="Enter Object Name"/>
                    <apex:inputText value="{!ObjectName}"/>
                </apex:pageBlockSectionItem>
                <apex:pageBlockSectionItem >
                    <apex:outputLabel value="Enter Name for Record"/>
                    <apex:inputText value="{!RecordName}"/>
                </apex:pageBlockSectionItem>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>
Apex Code :
public class InsertDynamicSobjectController
{
    public String ObjectName {get; set;}
   
    public String RecordName {get; set;}
   
    public InsertDynamicSobjectController()
    {
        ObjectName = '' ;
        RecordName = '' ;
    }
   
    public PageReference Save()
    {
        //use GlobalDecribe to get a list of all available Objects
        Map<string, schema.sobjecttype=""> gd = Schema.getGlobalDescribe();
        Set<string> objectKeys = gd.keySet();
        if(objectKeys.contains(Objectname.toLowerCase()))
        {
            try
            {
                //Creating a new sObject
                sObject sObj = Schema.getGlobalDescribe().get(ObjectName).newSObject() ;
                sObj.put('name' , RecordName) ;
                insert sObj ;
               
                PageReference pg = new PageReference('/'+sObj.Id) ;
                return pg ;
            }
            Catch(Exception e)
            {
                ApexPages.addMessages(e) ;
                return null ;
            }
        }
        else
        {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Object API name is invalid')) ;
            return null ;
        }
    }
}
</string></string,>

No comments:

Post a Comment