1

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?

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

| improve this answer | |
0

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.

| improve this answer | |
  • 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 – Vladyslav K Apr 18 '17 at 14:52
  • You can catch the exception in this case. try{ Database.SaveResult[] srList = Database.insert(accts, true); } catch(Exception ex){ // exception handling } – Arpit Sethi Apr 18 '17 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, ..." – Vladyslav K Apr 18 '17 at 14:58
  • You can easily identify the records which are causing error in catch block and return the status to lightning component – Arpit Sethi Apr 18 '17 at 15:04
  • how to do that? – Vladyslav K Apr 18 '17 at 15:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.