Find your content:

Search form

You are here

Assinging the Id field in Apex results in error

 
Share

I'm attempting to assign the Id of an account using the code below. However, I am getting an error with the following syntax. How can I set the Id field on an sobject in Apex?

Example 1:

myAccount.put('id', theId);

Example 2:

myAccount.id = theId;

Both of these examples result in error. Is there another way of setting the Id field?


Attribution to: Dedo

Possible Suggestion/Solution #1

NOT WORK

myAccount = [ SELECT Id FROM Account WHERE Id = :theId ];
myAccount.Id = theNewId;

WORK

myAccount = [ SELECT Id FROM Account WHERE Id = :theId ];

Account theAccount = new Account();
theAccount.Id = myAccount.Id;
theAccount.Name = 'New Name';
update theAccount;

Attribution to: Cray Kao

Possible Suggestion/Solution #2

You cannot assign a new object an Id that you desire.

Account acc = new Account(Id = 'someidhere');
acc.Field__c = 'someval';
update acc;

This works basically in place of querying for Account in the database, but you aren't actually setting the Id of the Account. It's basically a way to get around using a query to set fields.


Attribution to: dphil
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/32216

My Block Status

My Block Content