Aug 4, 2011

Inserting sObject Dynamically in Salesforce

I spend most of my time over Community, best place to learn and share knowledge. There are many questions related to sObject, and out of all a very interesting one is "How I can insert sObject record dynamically?"


I will provide a user interface with two text fields which will take "Object Name" and "Record Name" as string from user. And when I click on Save the record with Name entered should be inserted in the provided Object. Is this possible, of-course it is.


Here is the 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>

Here is the 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 gd = Schema.getGlobalDescribe();
        Set 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 ;
        }
    }
}


Code provided is flexible and you can extend it according to your need.

12 comments:

  1. Appreciable !! again with a useful Approach to create records directly but here we got a error message about Required fields but not provided option to fill those fields also on this page for Creating record.

    ReplyDelete
  2. Thanks a lot.. i was in a desperate need...

    ReplyDelete
  3. I got one ERROR in that Code.Please find Below ERROR.

    Error: InsertDynamicSobjectController Compile Error: line 16:39 no viable alternative at character '"' at line 16 column 39...

    pls Help me..

    ReplyDelete
    Replies
    1. you should change single quotes used in here..... which is in different font

      Delete
  4. Can you send your code to my mail id i can help you man.

    ReplyDelete
  5. Your solution is implemented in Apex. Is it possible to do similar thing in Java application by using Salesforce remote API?

    ReplyDelete
  6. is it possible to have same thing using java..?

    ReplyDelete
  7. Hi,
    I displayed custom objects and related custom fields with delete command link and edit command link using schema methods and wrapper class .My requirement is When i click delete command link this command link related custom object and custom field how to delete from database?

    please help me............

    ReplyDelete
  8. Hi sir,
    Good post sir, But I gave some field names(These field names dynamically add to visualforce page) related values. These fields related information how to save database dynamically.

    help me............

    ReplyDelete
  9. Error Error: InsertDynamicSobjectController Compile Error: unexpected token: 'Map' at line 16 column 8

    ReplyDelete
  10. How to create a new picklist with values dynamically using apex and VF, but that filed will not be in my Object. but I want this functionality working with apex input filed

    ReplyDelete
  11. Thank you very much for the post. Can you help me with the required fields as well?

    ReplyDelete