Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide a badge when the value is empty or zero

I would like my PrimeFaces p:badge not to be visible when the value is zero or empty. The following will display a badge with the value 0:

<p:badge value="0">
  <p:avatar label="Badge"/>
</p:badge>

And if I use an empty value an empty badge will be displayed:

<p:badge value="">
  <p:avatar label="Badge"/>
</p:badge>

Using the rendered attribute is no option as it will also hide the contents of the badge (the p:avatar in this case):

<p:badge rendered="#{bean.value ne '0'}">
  <p:avatar label="Badge"/>
</p:badge>
like image 928
Jasper de Vries Avatar asked Feb 02 '26 09:02

Jasper de Vries


1 Answers

PrimeFaces 10

Have a look at the HTML that is rendered when an empty value is used:

<div id="..." class="ui-overlay-badge">
  <span class="ui-badge ui-widget"></span>
  ...
</div>

You can simply hide empty elements using the :empty CSS selector. So you can hide empty badges using CSS like:

.ui-badge:empty { display: none; }

This CSS rule requires you to have an empty value in order to hide the badge. If you want to hide the badge if the value is 0, you could use a ternary expression to map 0 to empty:

<p:badge value="#{bean.value eq '0' ? '' : bean.value}">
  <p:avatar label="Badge"/>
</p:badge>

See also

  • How do I override default PrimeFaces CSS with custom styles?

PrimeFaces 11+

In PrimeFaces 11 the visible attribute is introduced. It can be used like:

<p:badge value="#{bean.value}" visible="#{not empty bean.value}">
  <p:avatar label="Badge"/>
</p:badge>

or

<p:badge value="#{bean.value}" visible="#{bean.value ne '0'}">
  <p:avatar label="Badge"/>
</p:badge>
like image 102
Jasper de Vries Avatar answered Feb 04 '26 01:02

Jasper de Vries



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!