Let's say I have a Contact, we'll say from Trigger.new. If I want to update its parent account, I skip a query by initializing it in memory like this.
Account acct = new Account(Id = contactInstance.AccountId);
update acct;
Now I'm trying to apply the same idea, but with dynamic apex using the new Type class. My object name comes from a custom setting. And because in this instance I'm working with Attachment, and ParentId in this instance, and ParentId can be one of many different types, I'm really trying to avoid the DB trip for a second query. Only, it doesn't work:
Type t = Type.fromName(setting.ObjType__c);
sObject myObjInstance = t.newInstance();
myObjInstance.put('Id',attachmt.ParentId);
etc...
An sObject Id will allow initialization, but it is not writable.
Anyone know any workarounds on this one? Or is it wait for API version 27?
Attribution to: pchittum
Possible Suggestion/Solution #1
The Schema.SObjectType class has a method specificially for setting an ID during sObject construction.
The second method on that listing is Schema.SObjectType.newInstance(Id), which
Constructs a new sObject of this type, with the specified ID. For the argument, pass the ID of an existing record in the database.
I believe this is exactly what you're looking for. If you need to go deeper and set other non-updateable fields in memory you may need to look into (ab)using JSON.deserialize
Attribution to: ca_peterson
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/3444