Wednesday, January 22, 2014

How to create instance of sobject dynamically? Normally the sobject is created like “Account a = new Account();”. But if you are in situation that you don’t know which sobject is going to be instantiated ? Means it will be decided at runtime, how you will handle it? Hint : Use Dynamic Apex.

How to create instance of sobject dynamically? Normally the sobject is created like “Account a = new Account();”. But if you are in situation that you don’t know which sobject is going to be instantiated ? Means it will be decided at runtime, how you will handle it? Hint : Use Dynamic Apex.

public SObject getNewSobject(String t)
{
                // Call global describe to get the map of string to token.
                Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();

                // Get the token for the sobject based on the type.
                Schema.SObjectType st = gd.get(t);

                // Instantiate the sobject from the token.
                Sobject s = st.newSobject();

                return s;
}

1 comment:

  1. Hi,
    I have one requirement,
    Actually using below code i save object record in database dynamically.But I this Record Fields information was not saved(Here will be add dynamically in my visualforce page).

    Schema.SObjectType targetType = Schema.getGlobalDescribe().get(strFieldName);
    SObject myObj = targetType.newSObject();
    insert myObj;

    Note:using above code related object record only created.

    but I gave some fields information here but those fields information is not saved in this record
    How to save fields information also related object record Dynamically?

    help me.....

    ReplyDelete