Salesforce Update Field without Query


I had someone call me today and ask about this – and I realized I haven’t shared this neat little nugget of knowledge on here yet.

Business case – I’m looping through stuff and I just need to update a value on another related record for some reason.  On the record I’m looping through, I have the Id of that related record (Lookup, WhoId, WhatId, OwnerId…whatever) – and my usual M.O. is to run an initial loop of my records, pull those Ids into a Set and the SOQL up a List<whatever>, and then just deal with it in the subsequent logic loop.

Totally works – but in the eternal pursuit of streamlining code to stay within the governor limits, I stumbled across this little gem:

Instead of running that initial SOQL query to build the list of related objects to update, you can do a neat little UPSERT (or UPDATE if you like) on a “new” object:

(Using a before-triggered Contact action – trying to update an Account field for this example)

List<Account> lstAccountsToUpdate = new List<Account>();
for(Contact c : trigger.new) {
// Regular Contact Logic (yes, it's pseudo-code)
if blah blah = etc etc, c.AddError(whatever);
// Update Account Object - pass the AccountId from the Contact object into the new object
Account accUpdate = new Account(Id=c.AccountId) 
accUpdate.Field_I_Want_To_Update__c = 'whatever';
lstAccountsToUpdate.add(accUpdate);
}
if(lstAccountsToUpdate.size() > 0) { upsert lstAccountsToUpdate; }

And there ya be – one less SOQL query you have to make.

Advertisements

2 thoughts on “Salesforce Update Field without Query

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s