2

Apex code developers guide says

   "The ID of an sObject is a read-only value and can never be modified explicitly in Apex unless it is cleared during a clone operation, or is assigned with a constructor" 

thinking this tried to assign the id for for an sobject Account in a method it found working. So I feel the documentation is wrong. Or is there any other views? Below is my method

   public void setAccountId()
   {
    Account a = new Account(id='0019000000sAr8H');
   }

2 Answers 2

2

Assigning the id in the constructor of the SObject does work. It is a standard technique to allow data to be updated without having to first query:

update new Account(
        Id = accountIdFromSomehwereOrOther,
        MyCustomField__c = 'New Value'
        );

The setAccountId method you include in your question will effectively do nothing as a local scope Account is being created and then not used for anything.

(If this code is called in a test, then with a hard-coded id that is already present in the org, you will have to resort the SeeAllData=true anti-pattern.)

3
  • Documentation says you can't set id no where apart from constuctor but I am able to set the id in a method which is my concern Commented Mar 31, 2014 at 8:23
  • 1
    @ShebinMathew The documentation perhaps isn't as clear as it could be; they mean it can be set in the constructor of the SObject (Account in your case). That constructor can be invoked anywhere in a class using the Account.
    – Keith C
    Commented Mar 31, 2014 at 8:38
  • Yes me to conclude this documentation doen't seems clear Commented Mar 31, 2014 at 9:17
1

Setting the ID in the account in your method will pass, and "run" but you will encounter an error should you then try to insert that account via DML as per below:

enter image description here

So whilst having the ID in your Account in memory might prove useful in some scenarios, you are not really setting the Salesforce ID (once the object gets to the Salesforce data layer).

Incidentally this line:

Account a = new Account(id='0019000000sAr8H');

IS the "constructor" for an Account object, and so it is perfectly valid as-per the documentation to set the Id here. Where this line then appears in your code is of no consequence to this rule.

Edit: from Keith's answer, I've always wondered what use this would have, and updating records without having to query sounds pretty plausible..!

2
  • I've added an example to clarify that its an update not an insert where setting the id is useful.
    – Keith C
    Commented Mar 31, 2014 at 8:41
  • Cool. I have added a little bit to clarify what it means by constructor.. Commented Mar 31, 2014 at 8:56

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .