Search code examples
jsfprimefacestooltipjsf-2.2

How to get rid of empty tooltips while displaying error messages on tooltips in PrimeFaces?


I display error messages somewhere on <p:tooltip> as follows.

<p:inputText id="text" value="#{bean.text}" required="true"/>

<p:tooltip for="text">
    <p:message for="text"/>
</p:tooltip>

Although it displays an error message the given tooltip, an empty/unnecessary tooltip is shown, when there is no error as can be seen in the following picture - beside the bottom right corner of the text box.

enter image description here

How to get rid of such empty tooltips? (I tried someway but it did not work)


Solution

  • It can be done by checking for an error message in the list java.util.List<FacesMessage> that can be obtained by using facesContext.messageList.

    The rendered attribute of <p:tooltip> can be set based on the error message/s found in the list for the associated component/s something along the line.

    rendered="#{not empty facesContext.getMessageList('clientId')}"
    

    A working code snippet :

    <h:form id="form">
        <p:panel id="panel">
            <p:inputText id="text" value="#{bean.text}" required="true"/>
    
            <p:tooltip for="text" rendered="#{not empty facesContext.getMessageList('form:text')}">
                <p:message for="text"/>
            </p:tooltip>
    
            <p:commandButton value="Submit" update="panel"/>
        </p:panel>
    </h:form>
    

    Or by using component binding. Such as,

    <p:inputText id="text" binding="#{inputComponent}" value="#{bean.text}"/>
    
    <p:tooltip for="text" rendered="#{not empty facesContext.getMessageList(inputComponent.clientId)}">
        <p:message for="text"/>
    </p:tooltip>
    

    Or even

    <p:inputText id="text" binding="#{inputComponent}" value="#{bean.text}"/>
    
    <p:tooltip for="text" rendered="#{not inputComponent.valid}">
        <p:message for="text"/>
    </p:tooltip>
    

    The last two cases are useful especially when the (input) component is enclosed within an iterating component like a <p/h:dataTable>, <p:dataGrid>, <p:dataList> (or even <ui:repeat>) where the uniqueness of enclosing components is determined based on the iterating row index of an iterating component such as, form:dataTable:0:text, form:dataTable:1:text, form:dataTable:2:text... and so on