You need to sign in to do that
Don't have an account?

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:
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
Note that even this 1 sole mention of OpportunityTeamMember fails an install:
Resulting in:
Missing Organization Feature: OpportunitySalesTeam
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.
Fortunately, what you seek here is simple:
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.
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.
Thanks guys! Both solutions are great and I like the method to easily create new sObjects of any type. Much appreciated!
To create a new sObject using a specific Id:
Where "i" is an Id variable containing the Id of the object you want to create.@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.