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

Create a record for generic sObject

I have the requirments to create record of generic sObject. How to do it?


A little more detail: a name of sObject holds in a variable, and i need to create record for it and insert it. I am stuck in this. Has anyone ideas? May be i miss some methods of object token or describe object?


Will be wery, wery thankful for help.

Best Answer chosen by Admin (Salesforce Developers) 

All Answers


looks like sObject is just an interface, not a class. Is methods to specify it to various type(to to hardcoded) exist? Or immediate creating of record...


Can you provide a little more detail of what you are trying to do. It sounds like you do have a object type that you want to use at some stage.  For example, you could use the global describe calls like the following, but I suspect your use case can be solved much more simply if I understand it better:



string lateBoundType = 'MyCustomObject__c'; 
sObject obj = Schema.getGlobalDescribe().get(lateBoundType).newSObject();
XmlDoc fields = //Create fields XML here
obj.Any = fields; 




I need to insert this record to database in the end.


The following code:



Map<String, Schema.SObjectType> m_objects = Schema.getGlobalDescribe();

sObject n = m_objects.get('account').newSObject();


Account acc = n.Create();

 causes error:


Method does not exist or incorrect signature: [SObject].Create()




Obj.Any - what is it? And what is the type XmlDoc? I cannot find it in docs


This was selected as the best answer

Hm, i had been sure that generic objects doesn't hold information about object represented. So(as i mean) it is necessary to convert it to specified type, and even didn't try Database.insert for sObject created from token.


But it works! Thank you a lot!


(As i check with system.debug, sObject contains information about object pointed... Sorry for a noop question)