How to display p:fileUpload invalidFileMessage in p:growl

Kishor Prakash picture Kishor Prakash · May 22, 2013 · Viewed 9.9k times · Source

I'm using <p:fileUpload> which is restricted to PDF only. However, the invalidFileMessage shows inside the <p:fileUpload> component. How can I show it in <p:growl> instead?

<p:fileUpload allowTypes="/(\.|\/)(pdf)$/"
              invalidFileMessage="File is Invalid. Only PDF files are allowed" />

Answer

BalusC picture BalusC · Dec 28, 2015

You can't handle this server side. The file type is validated at client side without hitting any code in server side. So, any suggestions which suggest to manually create FacesMessage and/or explicitly add <p:message(s)> are unthoughtful and untested.

You should use jQuery. It solves everything.

Based on the fileupload.js source code, your best bet is to listen on the fictional show event of the message container and then move the messages container to end of the form.

First extend $.show() to actually trigger the show event.

(function($) {
    var originalShowFunction = $.fn.show;
    $.fn.show = function() {
        this.trigger("show");
        return originalShowFunction.apply(this, arguments);
    };
})(jQuery);

Then simply create a listener on show event which basically runs when file upload messages appear and then parse every single message and use the renderMessage() function of the <p:growl> JS API. The below example assumes that you've a <p:growl widgetVar="growl"> somewhere in the same page.

$(document).on("show", ".ui-fileupload-content>.ui-messages", function() {
    $(this).children().hide().find("li").each(function(index, message) {
        var $message = $(message);
        PF("growl").renderMessage({
            summary: $(".ui-messages-error-summary", $message).text(),
            detail: $(".ui-messages-error-detail", $message).text()
        });
    });
});