【问题标题】:How to identify h:message within a datatable?如何识别数据表中的 h:message?
【发布时间】:2013-06-05 20:58:22
【问题描述】:

我正在尝试在它适用的数据表中的字段旁边放置一条错误消息,但我无法在支持 bean 中识别它。我的表单顶部有一个区域用于显示非特定于字段的错误/信息,但是当错误特定于某个字段(即“电子邮件”)时,我希望该消息出现在那里。

这是我的 XHTML:(为了清楚起见,我删除了表单的其他不相关部分)

<h:form styleClass="form" id="DeliveryOptionsForm">
   <h:dataTable value="#{sesh.delOptionList}" var="delOption">
      <h:outputText id="emailLabel" styleClass="#{(delOption.deliveryOption == 'EMAIL') ? '' : 'hide-field'}" value="Email  " />
      <h:message class="errorMessage" for="email" id="emailError" />
   </h:dataTable>
</h:form>

这是我的支持 bean:

FacesContext.getCurrentInstance().addMessage("DeliveryOptionsForm:email",
   new FacesMessage(FacesMessage.SEVERITY_ERROR, "Email address cannot be
   left blank when selecting email delivery.", null));

当我运行代码时,我收到错误消息:

[05/06/13 13:50:28:371 PDT] 00000026 RenderRespons W   There are some unhandled
FacesMessages, this means not every FacesMessage had a chance to be rendered.
These unhandled FacesMessages are: 
- Email address cannot be left blank when selecting email delivery.

有谁知道我做错了什么?我感觉消息的 clientId 设置不正确。

【问题讨论】:

  • 电子邮件字段在哪里?

标签: jsf datatable message


【解决方案1】:

您不应该在支持 bean 操作方法中进行验证。那是执行验证的错误位置。您应该在普通验证器中进行验证。

使用任一 JSF 内置验证:

<h:inputText id="foo" value="#{bean.foo}" required="true" requiredMessage="Please enter foo" />
<h:message for="foo" />

或者使用自定义验证器,在其中抛出 ValidatorException 和所需的消息:

<h:inputText id="foo" value="#{bean.foo}" validator="fooValidator" />
<h:message for="foo" />

@FacesValidator("fooValidator")
public class FooValidator implements Validator {

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) {
        // ...

        if (!valid) {
            throw new ValidatorException(new FacesMessage("Fail!"));
        }
    }

}

无论哪种方式,它都会自动出现在正确的消息组件中。


您没有在任何地方说明具体的功能要求,不幸的是您的代码 sn-p 不完整,但我的印象是,您实际上只想设置 required="true",只有当另一个属性具有特定值时。在这种情况下,只需执行以下操作:

required="#{delOption.deliveryOption == 'EMAIL'}"

【讨论】:

  • 感谢 BalusC。当我和其他人谈论这个时,我说我不能使用 required="true" 因为只有当下拉字段是'EMAIL'时才需要它......然后它击中了我。呃!感谢您的回复。我喜欢你的教程。你真的很了解你的东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-21
  • 1970-01-01
  • 2020-04-11
  • 1970-01-01
  • 2016-06-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多