Get the validation message for a specific component

前端 未结 2 1230
日久生厌
日久生厌 2021-01-14 13:48


        
相关标签:
2条回答
  • 2021-01-14 14:24

    The problem you will have with what you're planning is that a single component can have more than one message queued. What are you going to do then? For demonstration purposes, you can use

    <h:inputText id="myInputText"
                 title="#{facesContext.getMessageList('myInputText').get(0)}"
                 style="#{component.valid ? '' : 'border-color:red'}"
                 validator="#{MyBean.validate}"
                 required="true"
                 requiredMessage="required"
                 value="#{MyBean.value}" />
    

    EDIT : You should just move the logic into your backing bean:

    1. Implement a method that'll pull the detail from an available FacesMessage list, given a clientId

      public String getComponentMessageDetail(String clientId) {
          String detail = null;
          FacesContext ctxt = FacesContext.getCurrentInstance();
          List<FacesMessage> componentMessages = ctxt.getMessages(clientId);
      
          if (componentMessages != null && componentMessages.isEmpty() == false) {
              //returns the detail, from only the first message!
              detail = componentMessages.get(0).getDetail();
          }
      
          return detail;
      }
      
    2. Use the utility method in your view

       <h:inputText id="myInputText"
                    title="#{MyBean.getComponentMessageDetail('myInputText')}"
                    style="#{component.valid ? '' : 'border-color:red'}"
                    validator="#{MyBean.validate}"
                    required="true"
                    requiredMessage="required"
                    value="#{MyBean.value}" />
      
    0 讨论(0)
  • 2021-01-14 14:44

    How about this java method

    public String getComponentMessageDetail(String cid){
      FacesContext ctxt  =  FacesContext.getCurrentInstance();
      Iterator<FacesMessage> cm = ctxt.getMessages(cid);
      List<String> msg = new ArrayList<>();
      while(cm.hasNext()) {
        msg.add(cm.next().getDetail());
      }
      return String.join(" | ", msg);
    }
    

    to show everything what's in the message cache?

    Also in xhtml

    <h:inputText id="myInputText" title="#{MyBean.getComponentMessageDetail('yourFormId:myInputText'}" style="#{component.valid? '' : 'border-color:red'}" validator="#{MyBean.validate}" required="true" requiredMessage="required" value="#{MyBean.value} />
    

    it might be useful to put the name of your form-id in front of the input control's id. Otherwise the message list might have zero items, although there are some.

    Here is another way to quickly show validation messages: h:messages

    0 讨论(0)
提交回复
热议问题