Find your content:

Search form

You are here

Can I set sobject id in a method?

 
Share

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');
   }

Attribution to: Shebin Mathew

Possible Suggestion/Solution #1

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.)


Attribution to: Keith C

Possible Suggestion/Solution #2

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..!


Attribution to: Simon Lawrence
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/31374

My Block Status

My Block Content