8

I am inserting some new records using the apex class. I wrote some error conditions; if the error condition matches it will return null and show the error message on the VF page for which the record failed.

But I want to show all errors at once instead of showing the only error where it stopped.

Is it possible?

Class:

List<StandardProduct__c> spList = new List<StandardProduct__c>();
for(Integer i=1;i<list.size();i++){
    val = list[i].split(',');
    StandardProduct__c sp = new StandardProduct__c();
    sp.xyProd_c = val[0];
    sp.xyqty_c = val[1];
    sp.xyPrice= val[2];
    if(sp.xyProd_c != 'Test'){ // If one record enters this condition it is stopping here and just showing only error for one record
        error.add('Invalid prod' + sp.xyProd_c);
        return null;
    }
    if(sp.xyqty_c != null && sp.xyPrice != null)
    {
        spList.add(sp);
    }
    else if(some condition){ // The same as the first condition, showing only one error which entered here
        error.add('Failed to upload' + sp.xyProd_c);
        return null;
    }
}
1
  • 4
    yes, just don't return after finding the error that will allow your code to continue executing after the first error is found, if you don't want code to fire after one error is found you can use check that error map is empty (e.g. if(error.isEmpty) { // do something } Jul 15, 2016 at 19:51

2 Answers 2

8

You must return outside your loop.

for (/*iteration*/)
{
    if (/*failure condition*/)
    {
        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Fatal, 'message')));
    }
    // logic
    if (/*other failure condition*/)
    {
        ApexPages.addMessage(/*message construction*/);
    }
}
if (ApexPages.hasMessages(ApexPages.Severity.FATAL)) return null;
7

The problem is that you are returning from the function after you reach the first error. I can't see the whole picture from just what you've posted here, but part of the solution will be to remove the return null statements.

You must log in to answer this question.

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