简体   繁体   English

仅从验证规则中捕获错误消息并显示在VF页面中?

[英]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. 我已经设置了一些验证规则,并且使用此对象有一个VFpage。 I am able to capture the validation exception and display it on the VF page. 我能够捕获验证异常并将其显示在VF页面上。 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. 不幸的是,Ralph的帖子并非100%正确(请参阅Prady的评论,它不适用于页面顶部的验证错误),因此我写了这个答案来澄清。

  1. Add <apex:pageMessages/> tag to your page <apex:pageMessages/>标记添加到您的页面
  2. Enclose your DML statement with try catch like this: 将您的DML语句包含在try catch中,如下所示:
 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. 这将打印该语句引起的第一个DML错误,这通常是您想要的。 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. 您也可以尝试e.getMessage(),但这将显示其他用户不友好的信息(例如, Update failed. First exception on row 0 with id 001L000000QgmomIAB; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION等)。 The advantage of e.getDmlMessage is that it prints only the validation rule when the error is caused by validation rule. e.getDmlMessage的优点是,当错误是由验证规则引起时,它仅打印验证规则。

Visualforce can do this for you Visualforce可以为您做到这一点

  1. Add the <apex:pageMessages/> tag to your page. <apex:pageMessages/>标记添加到您的页面。 (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. 使用try {} catch(DMLException e) {}包围DML调用(当您捕获异常时,您将不会重定向到错误页面,但是Salesforce将为验证失败自动创建“ PageMes​​sage”。

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. 取而代之的是,用户将同时接收所有验证消息,而不必一次又一次地处理每个验证消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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