How to create an array in JSF EL?
Asked Answered
C

3

17

I want create an array in JSF EL. How can I do that? Is it even possible?

To illustrate what I am trying:

<rich:pickList addAllText="" addText="" removeAllText="" removeText="">
    <f:selectItems value="#{'Test', 'TestTest', 'TestTestTest'}" />
</rich:pickList>
Cumbersome answered 22/5, 2012 at 14:55 Comment(0)
G
22

If you're on EL 3.0 or newer, you can construct collections directly in EL.

<f:selectItems value="#{['Test','TestTest','TestTestTest']}" />

If you're not on EL 3.0 yet, you could solve this particular case with a fn:split() trick.

<html ... xmlns:fn="http://java.sun.com/jsp/jstl/functions">
...
<f:selectItems value="#{fn:split('Test,TestTest,TestTestTest', ',')}" />

Either way, this requires a minimum of JSF 2.0 for the support of List<T> in <f:selectItems>.

Gaulin answered 22/5, 2012 at 15:1 Comment(2)
Or, if using JSF 2, add Omnifaces to the project and use of:createArray :)Gillian
Great, this works, although I had to use xmlns:fn="http://java.sun.com/jsp/jstl/functions instead of http://java.sun.com/jsp/jstl/core.Cumbersome
P
4

It's possible with EL 3.0:

[1, 2, 3].toArray()

This creates a List first, and then converts it to an array.

At least with recent JSF versions you don't even need an array for f:selectItems, any Iterable will do. So:

<f:selectItems value="#{['Test', 'TestTest', 'TestTestTest']}" />

For more information about collection construction in EL see the EL 3.0 Specification - final release, 2.2 Construction of Collection Objects.

Pansie answered 14/7, 2015 at 10:0 Comment(0)
M
1

I am using ArrayUtils from apache to do this. first, register the ArrayUtils class as a bean so you can access it from EL.

<managed-bean>
    <managed-bean-name>arrayUtils</managed-bean-name>
    <managed-bean-class>org.apache.commons.lang3.ArrayUtils</managed-bean-class>
    <managed-bean-scope>application</managed-bean-scope>
</managed-bean>

then you can call ArrayUtils' methods:

#{myBean.aMethod(arrayUtils.add(ArrayUtils.EMPTY_INT_ARRAY, 1))}

the above code will not work if you can't access the constant EMPTY_INT_ARRAY. To this, i used primefaces p:importConstants component, not sure if can be done in plain JSF.

this is how i use it:

<p:importConstants type="org.apache.commons.lang3.ArrayUtils" var="ArrayUtils" />
Mandola answered 20/4, 2017 at 10:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.