26

I'm trying to update an account list and I need to get the Ids when the update fails.

I use the getId() method but for accounts which fail I get null.

It's an update so my account already has an Id.

Is it normal ? If it is, how can I get the Ids list of non-updated accounts ?

Here is my code :

List<Account> accountsList = [select Id from Account];

for(Account a : accountsList) {
    a.Name = 'Test',
}

List<Database.SaveResult> res = Database.update(accountsList, false);

for (Database.SaveResult s : res) {
    if (!s.isSuccess()) {
        system.debug(s.getId()); // I get null here
     } 
}

2 Answers 2

23

You can match the updated records with the Database.SaveResults using a list iterator, which will give you access to the original record:

List<Account> accountsList = [select Id from Account];

for(Account a : accountsList) {
    a.Name = 'Test',
}

List<Database.SaveResult> res = Database.update(accountsList, false);

//for (Database.SaveResult s : res) { //replaced by the following line
for (Integer i = 0; i < accountsList.size(); i++) {
    Database.SaveResult s = res[i];
    Account origRecord = accountsList[i];
    if (!s.isSuccess()) {
        system.debug(s.getId()); // I get null here
        system.debug(origRecord.Id); //This should be the Id you're looking for
     } 
}
0
5

See the SaveResult class docs: https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_database_saveresult.htm

and the example use:

// Iterate through each returned result
for (Database.SaveResult sr : srList) {
    if (sr.isSuccess()) {
        // Operation was successful, so get the ID of the record that was processed
        System.debug('Successfully inserted account. Account ID: ' + sr.getId());
    }
    else {
        // Operation failed, so get all errors                
        for(Database.Error err : sr.getErrors()) {
            System.debug('The following error has occurred.');                    
            System.debug(err.getStatusCode() + ': ' + err.getMessage());
            System.debug('Account fields that affected this error: ' + err.getFields());
        }
    }
}

The docs say that the getId() method only returns on success.

If this field contains a value, the object was successfully inserted or updated. If this field is empty, the operation was not successful for that object.

2
  • Yes I read it. Is there a workaround to get the IDs ?
    – SF_user
    Commented Oct 30, 2014 at 10:45
  • You could get the Ids of all the successfully updated accounts and then use that list to figure out which ones didn't update.
    – BarCotter
    Commented Oct 30, 2014 at 10:52

You must log in to answer this question.

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