18

How do I show JSF components if a list is not null and it has a size() > 0?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
developer
  • 9,116
  • 29
  • 91
  • 150
  • 1
    http://stackoverflow.com/questions/1985718/how-do-i-display-a-message-if-a-jsf-datatable-is-empty It has clear explanation for everything you need and more. – kinkajou May 03 '13 at 14:06

3 Answers3

53

EL offers the empty operator which checks both the nullness and emptiness of an object.

Thus, this should do:

<h:dataTable value="#{bean.list}" var="item" rendered="#{not empty bean.list}">

No need for a clumsy double check on both null and size() as suggested by other answers.

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
2

use rendered attribute. most of the components have this attribute.This attribute;s main purpose is to render components conditionally.

<h:dataTable value="#{bean.list}" rendered="{bean.list !=null &amp;&amp; bean.list.size()>0}" >

In the above piece of jsf code, datatable would only be rendered when list is not null and the size of list is greater than 0

PermGenError
  • 45,977
  • 8
  • 87
  • 106
  • 2
    The ugly `&&` can easily be replaced by the more readable `and`. Even more, the whole double check can easily be replaced by a single operator: `empty`. – BalusC May 03 '13 at 14:22
  • @BalusC true, & is ugly. as i commented under your question i din't know that empty operator existed. thanks for your feedback. i indeed find it rather ugly using &amp while applying conditional rendering to my components. :) – PermGenError May 03 '13 at 14:24
1
<h:outputText value="No Data to Display!" rendered="#{empty list1.List2}" />
<a href="#">
<h:outputText value="Data is present" rendered="#{not empty list1.List2}" /></a>

Or

<h:outputText value="#{not empty list1.List2 ? 'Data is Present' : 'No Data to Display'}" style="color:blue"/>
Chinmoy
  • 1,391
  • 13
  • 14