You need to sign in to do that
Don't have an account?
Dynamic Object Creation
I'm not sure if this is possible, but is there any way I can make a new instance of an object if I only have the type of the object saved as a string? What I mean is, I have a string called sObjectType which gets set on a visual force page and contains either "Account" or "Contact" or any other type of salesforce object. In my apex method I need to make a new instance of this object for insertion but the catch is that I can't do Account a = new Account() or anything like that directly since all I know about the type is whatever's in my sObjectType variable. Given this information, can I make this happen?
Something like this maybe?
String obj = 'some object from vf page'; obj variable = new obj(); List<obj> objList = new List<obj>(); objList.add(variable); insert objList;
Thanks in advance!
I think this is what you are after:
Check out the Dynamic Apex chapter in the Apex documentation for more information.
All Answers
I think this is what you are after:
Check out the Dynamic Apex chapter in the Apex documentation for more information.
Hay thanks! That looks really promising. What about a list? If I want to insert a list of those objects whose type is not known right away, how would I make that list? Thank you again.
What about it? You should be able to modify that example to produce a list fairly easily by calling the newSobject() method on the token however many times you need to. Your list will need to be homogeneous though as the DML operation doesn't support heterogeneous lists of sobjects today, i.e. a list with 2 accounts, 3 contacts, etc.
You could also leverage the clone() method on sobject and just use that code as is.
hey mtbclimber could you please help me.
I also want to create object dynamically by the value selected from picklist.
Where should i make changes in your existing code for it?
My final output should be i need an object 'Account' created if my selectedValue in picklist is 'Account'.
From ur code i am not understanding where should i integrate it with my controller.
Please help would be grateful.
Thanks.