Oh my god. It's full of code!

Apex update sobject without querying for it first

Hey all,
This is just another quick handy tip. Sometimes when working with Apex you will want to update an object you already know the ID of without having to query for it first. Say for example you modify an account related to a contact. You already know the ID of the account, and don’t want to waste an SOQL query having to query for it. You might think you can do this

list<contact>  theContacts = [select id, accountid, name from contact limit 5];
list<account> updateAccounts = new list<account>();
for(contact con : theContacts)
{
    account thisContactsAccount = new account();
    thisContactsAccount.id = con.accountId;
    thisContactsAccount.name = 'blah blah blah';
    updateAccounts.add(thisContactsAccount);
}
update updateAccounts;

But you can’t. You’ll get the error ‘Field is not writeable: Account.Id’.
Instead, you can do this!

list<contact>  theContacts = [select id, accountid, name from contact limit 5];
list<account> updateAccounts = new list<account>();
for(contact con : theContacts)
{
    account thisContactsAccount = new account(Id=con.accountid);
    thisContactsAccount.name = 'blah blah blah';
    updateAccounts.add(thisContactsAccount);
}
update updateAccounts;

That will work and allow you to create a reference to an sObject without having to query for it first. Pretty handy sometimes. Anyway, just one of those quick time saving tips that isn’t super obvious at first. Hope this helps someone!

One response

  1. adelaby

    Helped a lot, thanks 🙂

    March 12, 2015 at 1:39 pm

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