Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

jsf - Automatically show validation messages in p:dialog on validation failure

I want to present validation messages and messages from backing bean in <p:dialog> component. In my JSF page I have following dialog defined:

<p:dialog widgetVar="messageDialog" id="msgDialog" modal="true" appendToBody="true">
    <h:form id="messageForm">
        <p:messages id="messagesInDialog" />
        <p:commandButton value="OK" onclick="messageDialog.hide()" />
    </h:form>
</p:dialog>

I execute the following code after appending some message in backing bean:

RequestContext.getCurrentInstance().execute("messageDialog.show()");

and it works fine.

However, I also want to display bean validation messages in this dialog. Messages are appended to <p:message> component afer validation, but I have no idea how to display this dialog after validation failure.

How can I achieve this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use the visible attribute of <p:dialog> to specify whether the dialog should show up by default or not. You can check by FacesContext#isValidationFailed() if there's a validation failure or not.

So, in a nutshell:

<p:dialog id="msgDialog" widgetVar="messageDialog" modal="true" appendToBody="true"
    visible="#{facesContext.validationFailed}">
    <p:messages id="messagesInDialog" />
    <p:button value="OK" onclick="messageDialog.hide()" />
</p:dialog>

(note that I simplified the unnecessary h:form and p:commandButton by a p:button)

Which is then to be updated by:

<p:commandButton value="submit" update=":msgDialog" />

Or by just placing it inside a <p:outputPanel autoUpdate="true"> so that it auto-updates itself on every ajax request without the need to specify it in every update attribute:

<p:outputPanel autoUpdate="true">
    <p:dialog id="msgDialog" widgetVar="messageDialog" modal="true" appendToBody="true"
        visible="#{facesContext.validationFailed}">
        <p:messages id="messagesInDialog" />
        <p:button value="OK" onclick="messageDialog.hide()" />
    </p:dialog>
</p:outputPanel>

See also:


Unrelated to the concrete problem, to cover non-validation messages, such as those global messages which you add in the action method, rather check instead if FacesContext#getMessageList() is not empty.

<p:dialog ... visible="#{not empty facesContext.messageList}">

This will then show the dialog when there is any message. This way that RequestContext#execute() call is unnecessary.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...