I am developing lightning component, on which user enters data in table and creates multiple records. If some records do not pass validation - row has to be highlighted with red. For this I need to determine which element in list does not pass validation. https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_database_saveresult.htm - From this example I see that I can know what record raised error:

Account[] accts = new List<Account>{
    new Account(Name='Account1'),
    new Account() // <- causes error

Database.SaveResult[] srList = Database.insert(accts, false);

for (Database.SaveResult sr : srList) {
    if (!sr.isSuccess()) {        
        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());

But since allOrNone = false - valid records would be inserted. Is it possible to not insert any records if some of them are not valid and without raising exception?

  • Comments are not for extended discussion; this conversation has been moved to chat.
    – Adrian Larson
    Apr 18, 2017 at 17:34

2 Answers 2


Since you need to know which rows, you need to set a savepoint, gather the records that caused the error and the reasons, then rollback the DML. That will undo everything that was done. Then you can return those Ids and messages is either a Map<Id,String> or a custom error class. Then consume it in your component


If I am getting it right, you do not want to allow partial success. you can use allOrNone= true, which will not allow to insert records if validation fails for any of the records.

  • In this case code will throw error and SaveResult will be null, so I will be not able to determine what record is not correct Apr 18, 2017 at 14:52
  • You can catch the exception in this case. try{ Database.SaveResult[] srList = Database.insert(accts, true); } catch(Exception ex){ // exception handling } Apr 18, 2017 at 14:57
  • but it is not good to parse message like this: "System.DmlException: Insert failed. First exception on row 2; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, ..." Apr 18, 2017 at 14:58
  • You can easily identify the records which are causing error in catch block and return the status to lightning component Apr 18, 2017 at 15:04
  • how to do that? Apr 18, 2017 at 15:06

You must log in to answer this question.

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