Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PrimeFaces growl change color dynamically

Is there a way to change dynamically the background of the PrimeFaces growl component? I want to be able to show a red background when it's an error and a green background when is a success.

Thanks in advance.

like image 705
Daniel Rojas Avatar asked Dec 07 '22 00:12

Daniel Rojas


1 Answers

The above solution only works if you add only one message at a time to the context. If you add more than one message, all the growl items will be colored by the last message's severity. Please follow the link below for furher details about the issue.

(Turkish content, you may need to translate it)
Change PrimeFaces growl background color dynamically

In order to solve this problem, you should find growl items by icon style (PrimeFaces changes only growl icons for different severity levels) and add a custom stylesheet class to the grand-parent of the growl icon's html element in order to achieve different background colors.

First define the script below (which adds custom css classes to the grand-parents):

<script>
   function init () { 
      $(".ui-growl-image-info").parent().parent().addClass("g-info");
      $(".ui-growl-image-warn").parent().parent().addClass("g-warn");
      $(".ui-growl-image-error").parent().parent().addClass("g-error");
      $(".ui-growl-image-fatal").parent().parent().addClass("g-fatal");
   }
</script>

and add the below style definition to your page:

<style>
    div[id="growlForm:growl_container"] > div[class~="g-fatal"] {
    background-color: black !important;
    }

    div[id="growlForm:growl_container"] > div[class~="g-error"] {
    background-color: red !important;
    }

    div[id="growlForm:growl_container"] > div[class~="g-warn"]{
    background-color: orange !important;
    }

    div[id="growlForm:growl_container"] > div[class~="g-info"]{
    background-color: green !important;
    }

    .ui-growl-image-info ~ .ui-growl-message {
    color:#fff;
    }
    .ui-growl-image-error ~ .ui-growl-message {
    color:#fff;
    }
    .ui-growl-image-warn ~ .ui-growl-message {
    color:#fff;
    }
    .ui-growl-image-fatal ~ .ui-growl-message {
    color:#fff;
    }
 </style>

And finally, attach init() method to the element which adds messages to the context.

<p:commandButton value="Show" actionListener="#{someBean.someMethod}" oncomplete="init();"/>

And the result is :)

Dynamic Growl Background Color in PrimeFaces

Source Code of the Project

Hope this helps anybody.

like image 146
ngc4151 Avatar answered Mar 03 '23 22:03

ngc4151