4

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?

6

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

| improve this answer | |
  • Awesome! That's what I needed. Will look into JSON abuse at some other date. :-) – pchittum Oct 17 '12 at 23:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.