14

What is the "proper" way of getting an object from an Id? The method I use at the moment is SOQL, and that feels wrong.....

Example:

Account account = [SELECT Id FROM Account WHERE Id=:inserted.Account__c];

account.Membership_End__c = Date.today();
account.Membership_Active__c = false;
update account;

I feel like this psudo-code should work:

Account account = new Account(inserted.Account__c);
account.Membership_End__c = Date.today();
account.Membership_Active__c = false;
update account;

So do I just have a massive blind spot, or is this it?

19

If you already know the ID of the SObject you want to update then you're right, there's no need to waste a query just to get an SObject instance to work with.

Your sample code is very close to working, but you need to remember that the constructors for SObjects are special and accept named arguments, something unique to them in all of apex. Your sample code could be updated to work like so:

Account account = new Account(
    Id = inserted.Account__c,
    Membership_End__c = Date.today(),
    Membership_Active__c = false
);
update account;

or even turned into a single statement:

update new Account(
        Id = inserted.Account__c,
        Membership_End__c = Date.today(),
        Membership_Active__c = false
);

As @BritishBoyInDC points out in recent API versions you could also write this in a longer form. There's not much benefit to doing this in your case, but there are some cases where it can be useful:

Account account = new Account();
account.Id = inserted.Account__c;
account.Membership_End__c = Date.today();
account.Membership_Active__c = false;
update account;
  • That was pretty quick :) – Boris Bachovski Oct 8 '13 at 0:13
  • 2
    I had to do something while my unit tests were running! Don't forget to upvote the question too, it's a good one. – ca_peterson Oct 8 '13 at 0:15
  • 4
    xkcd.com/303 – Mitch Hunt Oct 8 '13 at 0:50
  • 2
    Would just add that the Id field is now writeable since Spring 13, so you don't have to set it in the constructor like we used to... developer.force.com/releases/release/Spring13/… – BritishBoyinDC Oct 8 '13 at 2:25
  • 2
    Just to clarify (and quite frankly to be a little pedantic), "writeable" in this context means that you can write to it in memory in Apex, but the field is not writeable in the DB, i.e. I am not allowed to write my own record ID on insert. – pchittum Nov 11 '15 at 11:18

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.