To update records, you'll need to issue an update
statement against sObject(s) that already have a value for the Id
field.
Bouncing off the last code example. Say we're asked to find the most newest Account and update the description to say ''Latest Account":
// Retrieve the Account record from the database Account latestAccount = [Select Id, Name, Description FROM Account ORDER BY CreatedDate DESC LIMIT 1]; //Set the description field latestAccount.Description = 'Latest Account'; // issue the DML operation update latestAccount;
3 lines! That's all it takes. This worked because the Id
field is part of the latestAccount
variable set when the SOQL runs. This would not have worked:
// Creating a sObject in memory Account latestAccount = new Account(Name='Apple Inc'); latestAccount.Description = 'Latest Account'; // issue the DML operation update latestAccount;
We'll get back a DML Exception. System.DmlException: Update failed. First exception on row 0; first error: MISSING_ARGUMENT, Id not specified in an update call: []
.
The Id
must be specified. The same is true for lists of sObject records:
List<Account> accountsWithoutType = [SELECT Id, Name, Type FROM Account WHERE Type = '']; for (Account acc : accountsWithoutType) { acc.Description = 'Basic'; } Account newAcc = new Account(Name = 'Apple', Type='Basic'); accountsWithoutType.add(newAcc); update accountsWithoutType;
Now that doesn't mean you can only update sObject records that are set from a SOQL query.
public static void updateAccountDescriptionById(String newDescription, Id existingAccountId){ Account acc = new Account(); acc.Id = existingAccountId; acc.Description = newDescription update acc; }
This works! The id
field just needs to be set with a valid Id. It doesn't matter how it gets set.
You'd still get the same System.DMLException. All the records being processed by the update statement must have an id.