How to show JSF components if list is not null and has size() > 0
Asked Answered
W

3

18

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

Woundwort answered 3/5, 2013 at 13:59 Comment(1)
stackoverflow.com/questions/1985718/… It has clear explanation for everything you need and more.Perea
Z
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:

Zest answered 3/5, 2013 at 14:19 Comment(1)
hmm, interesting, never knew that there was an Empty operator in EL. +! :)Tacit
T
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

Tacit answered 3/5, 2013 at 14:5 Comment(2)
The ugly &amp;&amp; can easily be replaced by the more readable and. Even more, the whole double check can easily be replaced by a single operator: empty.Zest
@Zest true, &amp; 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. :)Tacit
B
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"/>
Brownley answered 11/1, 2018 at 8:39 Comment(2)
How is this better (in the context of the questionj) than the accepted answer?Hydrograph
@Hydrograph - It does add valid alternatives, which is helpful.Mingmingche

© 2022 - 2024 — McMap. All rights reserved.