Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display <p:fileUpload> validation errors inside <p:messages>

I have a hidden <p:fileUpload> which is opened via <h:outputLabel>.

<p:messages id="message" autoUpdate="true" />

<h:form id="form">

    <p:fileUpload id="file-input" auto="true"
        allowTypes="/(\.|\/)(gif|jpe?g|png)$/" sizeLimit="10"
        invalidSizeMessage="wrong size" fileUploadListener="#{bean.image}"
        update="@form message" style="display: none;"
        invalidFileMessage="wrong file" />

    <h:outputLabel for="file-input_input">
        <h:graphicImage name="images/dummy.jpg" />
     </h:outputLabel>

    <h:outputText value="#{bean.file.fileName}" />
    <br />
    <h:outputText value="#{bean.file.size}" />
</h:form>

Unfortunately, no messages are displayed after validation failed (e.g invalid size or invalid file). Those messages are displayed inside the <p:fileUpload> content box instead of in <p:messages>.

How can I display those messages inside <p:messages> instead of inside <p:fileUpload>?

like image 724
alexander Avatar asked Jul 30 '26 14:07

alexander


1 Answers

The validation is performed fully client side without hitting the server. So you can't control this from server side on.

The message container of the <p:fileUpload> is available via messageContainer property of the widget variable. Simple let jQuery move it into the <p:messages> when clicking the label:

<p:messages id="messages" ... />

<h:form>
    <p:fileUpload id="file-input" widgetVar="file-input" ... 
        styleClass="ui-helper-hidden" />
    ...
    <h:outputLabel for="file-input_input" ...
        onclick="PF('file-input').messageContainer.appendTo($('#messages'));" />
</h:form>

(I only renamed <p:message id> to be more sensible, and used a PrimeFaces specific class to hide it instead of an inline style)

The onstart and oncomplete attributes of <p:fileUpload> weren't usable as they are only executed when the client side validation has passed and the file upload request is actually sent.

like image 188
BalusC Avatar answered Aug 02 '26 09:08

BalusC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!