function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
jkucera2jkucera2 

How do I create a new sObject with a dynamic type? Error: Type cannot be constructed: sObject

I have an app that does stuff with OpptyTeamMembers, but that app can't be installed in orgs that dont' have it turned on, and I don't want to have to create 2 versions of the app.

 

My solution to this is to make all the opptyTemMember references dynamic using sObjects, but I'm stuck on how to create new records as I get an error trying to do this:

sObject ot=new sObject();

 Error: Type cannot be constructed:sObject

 

I can't simply copy & update an existing opptyTeamMember as the ID fields aren't updatable.  

 

I realize the Apex guide says this isn't possible:

The new operator still requires a concrete sObject type, so all instances are specific sObjects.

 

...but an old thread on the partner API hints that it should be possible:

http://boards.developerforce.com/t5/NET-Development/getting-error-when-using-create-with-the-Partner-wsdl/m-p/27483/highlight/true

Best Answer chosen by Admin (Salesforce Developers) 
hchhch

You can use the following code to create an SObject dynamically:

sObject sObj = Schema.getGlobalDescribe().get(ObjectName).newSObject() ;

 

where the "ObjectName" is the name of the Object which you want to initialize.

All Answers

jkucera2jkucera2

Note that even this 1 sole mention of OpportunityTeamMember fails an install:

sObject ot=new OpportunityTeamMember();

 Resulting in:

Missing Organization Feature: OpportunitySalesTeam

jkucera2jkucera2

My final workaround if there isn't a solution, will be to remove all tests associated with OpptySalesTeams as they are the only thing in the app that require the inserting of new records to verify behavior.  I'll still have 79% code coverage without them, but would rather not go that route. 

mulvelingmulveling

Fortunately, what you seek here is simple:

 

public class UndefinedSObjectTypeException extends Exception {}

// typeName must be a valid API name (i.e. custom objects should be suffixed with "__c"):
public static SObject newSObject(String typeName) {
    Schema.SObjectType targetType = Schema.getGlobalDescribe().get(typeName);
    if (targetType == null) {
        // calling code should usually handle this exception:
        throw new UndefinedSObjectTypeException('The requested SObject type [' + typeName + 
                '] cannot be constructed; it is not configured on this org.');
    }
    // SObjects offer the only way in Apex to instantiate an object with a type determined at 
    // runtime -- you can optionally pass an Id argument to instantiate an SObject for an 
    // existing record:
    return targetType.newSObject();
}

public static SObject newOpptyTeamMember() {
    return newSObject('OpptyTeamMember');
}

System.debug('Created new instance of: ' + newOpptyTeamMember().getSObjectType());

 

mulvelingmulveling

Also, FYI: a production solution based on the above should cache the global describe result (it's a Map<String, Schema.SObjectType>), or pass it in as context (i.e. if you want to calculate it elsewehere, for reuse in other places) so that you don't run into limits when instantiating many instances per transaction. 

hchhch

You can use the following code to create an SObject dynamically:

sObject sObj = Schema.getGlobalDescribe().get(ObjectName).newSObject() ;

 

where the "ObjectName" is the name of the Object which you want to initialize.

This was selected as the best answer
jkucerajkucera

Thanks guys!  Both solutions are great and I like the method to easily create new sObjects of any type.  Much appreciated!

narsavagepnarsavagep

To create a new sObject using a specific Id:

sObject sObj = i.getSObjectType().newSObject(i);
Where "i" is an Id variable containing the Id of the object you want to create.
Izzy DeveloperIzzy Developer
Does anyone know how to update an sobject dynamically?
narsavagepnarsavagep

@Izzy: 
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_SObjects.htm
Use ".get()" and ".put()" on the sObject variable to get/set the values.  

Izzy DeveloperIzzy Developer
@narsavagep -- Thank you. I ran across that material yesterday, but sometimes it takes someone else to make me look again, acknowledge, and confirm what I actually saw. I had blinders on. Again, thank you.
Nicholas ZozayaNicholas Zozaya
@hch YES!!!