简体   繁体   中英

Capture only the error message from validation rule and display in VF page?

i have set up a few validation rules and i have a VFpage using this object. I am able to capture the validation exception and display it on the VF page. The issue is that it shows message as

   " Upsert Failed : First exception on row 0: first error;

     FIELD_CUSTOM_VALIDATION_EXCEPTION Quantity cannot be empty

Is there a way i can just capture the error message in validation Rule "Quantity cannot be empty" ?

Thanks

Unfortunately, Ralph's post is not 100% correct (see Prady's comment that it won't work for top-of-page validation errors), so I write this answer to clearify.

  1. Add <apex:pageMessages/> tag to your page
  2. Enclose your DML statement with try catch like this:
 try{ update account; //or anything else } catch(System.DmlException e) { ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, e.getDmlMessage(0))); } 

This will print the first DML error that statement caused which is usually what you want. You can also try e.getMessage() but this will show additional information (like Update failed. First exception on row 0 with id 001L000000QgmomIAB; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION etc.) which is not user friendly. The advantage of e.getDmlMessage is that it prints only the validation rule when the error is caused by validation rule.

Visualforce can do this for you

  1. Add the <apex:pageMessages/> tag to your page. (This is the container that displays any error messages if present)
  2. Surround your DML call with try {} catch(DMLException e) {} (When you catch the exception you won't get redirected to the error pages, but salesforce will automatically create a "PageMessage" for the validation failure.

If you use this:

ApexPages.addMessages(e);

instead the user will receive all validation messages at the same time instead of having to work through each one, one at a time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM