How can I pass a list literal to f:selectItems? - jsf

For example:
<h:selectManyCheckbox
id="literalOptions"
value="firstOption">
<f:selectItems value="[firstOption, secondOption, thirdOption]"/>
</h:selectManyCheckbox>
this doesn't work, but you get the idea?
I want to pass literal (string-type) list options (not necessarily but possibly retrieved from a bean property as a String), the [a,b,c] list-syntax probably isn't correct, but which is?
Or, alternatively, how can I pass a list literal to a custom component I create that passes this literal to f:selectItems which I use internally in my custom component? That is, how can I create a custom component that accepts such a literal for ad hoc definition of list values by the component user.

If you're on Java EE 6, use JSTL fn:split() trick.
<html ... xmlns:fn="http://java.sun.com/jsp/jstl/functions">
...
<h:selectManyCheckbox value="firstOption">
<f:selectItems value="#{fn:split('firstOption,secondOption,thirdOption', ',')}"/>
</h:selectManyCheckbox>
If you're on Java EE 7, use EL 3.0 collection literal.
<h:selectManyCheckbox value="firstOption">
<f:selectItems value="#{['firstOption', 'secondOption', 'thirdOption']}"/>
</h:selectManyCheckbox>
You was close, you just had to quote the string values and to put the whole in #{...}.
Note that specifying a literal in <h:selectManyCheckbox value> would fail with a PropertyNotWritableException on submit, but that's a different problem.

Related

jsf methods expression valuechanged event don't work or work different in inputtext and selectOneMenu

i'm new with jsf technology and use of managed bean.
I'm reading the Java Platform, Enterprise Edition The Java EE Tutorial release 7 but it seems to be not clear, i have different problem how in example below :
<h:selectOneMenu value="#{user.age}" onchange="submit()" valueChangeListener="#{user.ageChanged}">
<f:selectItems value="#{user.ages}" />
<f:converter converterId="javax.faces.Integer"/>
</h:selectOneMenu>
<h:inputText id="name" value="#{user.name}" required="true" validator="#{user.validateName}" valueChangeListener="#{user.nameChanged}" onchange ="submit()" />
the first one do the job, but the second not it displays:
'managedBean.User' does not have the property nameChanged.
but ageChanged is not a property but the first example do the job
but i'm using method expression to refers method nameChanged that it's present on the bean user,
i'm confusing, too with use or not of the bracket on methods expression:
valueChangeListener="#{user.nameChanged}" or valueChangeListener="#{user.nameChanged()}" what is the properly way to use methods expression?
i say this cause in another example having method with no parameters, the two approaches had different behave, first the same error about property missing, the second Apparently worked.
any help? a speak about method expressions it's appreciated to. thank you.

<h:selectOneMenu with conditional <f:selectItems shows options twice

I want to use a selectOneMenu to have a user choose a value. In some cases I want to disable one of the values shown in the menu. I tried using render on both the selectItems as well as selectOneMenu as well as added a ui:fragment around the Menu but I always get all the values from both lists shown. Any ideas how to prevent that?
Here my current last try that again resulted in twice the list and the item in question once enabled and once disabled in it:
<ui:fragment rendered="#{cc.attrs.showP==true}">
<h:selectOneMenu id="type" binding="#{cc.type}">
<f:selectItems value="#{typeDAO.findAll()}"/>
</h:selectOneMenu>
</ui:fragment>
<ui:fragment rendered="#{cc.attrs.showP==false}">
<h:selectOneMenu id="type" binding="#{cc.type}">
<f:selectItems value="#{typeDAO.findAll()}" var="item" itemDisabled="#{item=='P'}"/>
</h:selectOneMenu>
</ui:fragment>
Your concrete problem is caused because you're binding physically multiple components to the same variable.
<h:selectOneMenu ... binding="#{cc.type}" />
<h:selectOneMenu ... binding="#{cc.type}" />
If the getter behind binding returns non-null, then JSF will use it instead of creating a new one. Basically, the second tag will reuse the component created in the first tag and set/add all attributes/items to it.
Your particular case can be solved in at least two ways:
Use JSTL to build the JSF component tree conditionally instead of using JSF to render the HTML output conditionally. You shouldn't have physically multiple components in the JSF component tree sharing the same binding let alone the same id.
<c:if test="#{cc.attrs.showP}">
<h:selectOneMenu id="type" binding="#{cc.type}">
...
</h:selectOneMenu>
</c:if>
<c:if test="#{not cc.attrs.showP}">
<h:selectOneMenu id="type" binding="#{cc.type}">
...
</h:selectOneMenu>
</c:if>
Make your code DRY. I.e. get rid of all code duplication.
<h:selectOneMenu id="type" binding="#{cc.type}">
<f:selectItems value="#{typeDAO.findAll()}" var="item" itemDisabled="#{not cc.attrs.showP and item eq 'P'}" />
</h:selectOneMenu>
See also:
How does the 'binding' attribute work in JSF? When and how should it be used?
JSTL in JSF2 Facelets... makes sense?
Guess I found it - bit weird to answer my question though. I think it's because the possible values of the menu are created before the rendered attributes are evaluated and since I did bind both menus to the same variable/id I got all items of the two menus. Thus I now used different names and then in my composite component have some logic that checks which one is used and continues to use the right value. Works :-)
Bit weird to me is this thing that as a developer u have to know when the attribute list is built in comparison to when the rendering happens. I recently had a similar issue with foreach and repeat. Is there any way to know these things as part of some overarching concept that I can remember or is that really case by case?
Thanks guys!

Setting f:setPropertyActionListener value with a f:param value

I'm trying to use the setPropertyActionListener tag to set a value in my backing bean. However, it doesn't work as I expected.
Context: userService is an instance of my backing bean, which contains an int member, reqID. This, in turn, is the key to a map of objects that belong to a class called User. I'm trying to create a page that will list all instances of User, and provide a button to visit a separate view that shows that particular User's information. To do this, I'm attempting to set userService.reqID to the id of the chosen User so it can generate a reference to that user for the next view (which is done in the call userService.toUserInfo).
If I use the xhtml snippet below:
<ui:define name="content">
<h:form>
<h:panelGrid>
<ui:repeat value="#{userService.UserList.getUserList()}" var="user">
<li>
<h:outputText value="#{user.name}" />
<h:commandButton value="View details of #{user.name}" action="#{userService.toUserInfo}">
<f:param name="id" value="#{user.id}" />
<f:setPropertyActionListener target="#{userService.reqID}" value="#{id}"/>
</h:commandButton>
</li>
</ui:repeat>
</h:panelGrid>
</h:form>
</ui:define>
The tag does not appear to evaluate id correctly and I get a Null Pointer Exception.
Earlier, I tried changing my setPropertyActionListenerTag so it read out as:
<f:setPropertyActionListener target="#{userService.reqID}" value="id"/>
which gave me an error, because the tag was sending the string "id" as opposed to the int value of the parameter.
Is there some way to force f:setPropertyActionListener to evaluate the expression under value? Or is there another tag that will allow me to do this?
Also, is ui:param used appropriately here?
The <f:param> (and <ui:param>) doesn't work that way. The <f:param> is intented to add HTTP request parameters to outcome of <h:xxxLink> and <h:xxxButton> components, and to parameterize the message format in <h:outputFormat>. The <ui:param> is intented to pass Facelet context parameters to <ui:include>, <ui:decorate> and <ui:define>. Mojarra had the bug that it also behaves like <c:set> without a scope. This is not the intented usage.
Just use <c:set> without a scope if it's absolutely necessary to "alias" a (long) EL expression.
<c:set var="id" value="#{user.id}" />
Put it outside the <h:commandLink> though. Also in this construct, it's kind of weird. It doesn't make the code better. I'd just leave out it.
<f:setPropertyActionListener ... value="#{user.id}" />
See also:
Setting ui:param conditionally
what is the scope of <ui:param> in JSF?
Defining and reusing an EL variable in JSF page
Unrelated to the concrete problem, if you're using EL 2.2 (as you're using JSF 2.2, you undoubtedly are as it requires a minimum of Servlet 3.0, which goes hand in hand with EL 2.2), then just pass it as bean action method argument without <f:setPropertyActionListener> mess. See also a.o. Invoke direct methods or methods with arguments / variables / parameters in EL and How can I pass selected row to commandLink inside dataTable?
<h:commandButton ... action="#{userService.toUserInfo(user.id)}">
On again another unrelated note, such a "View user" or "Edit user" request is usually idempotent. You'd better use <h:link> (yes, with <f:param>) for this. See also a.o. Creating master-detail pages for entities, how to link them and which bean scope to choose and How to navigate in JSF? How to make URL reflect current page (and not previous one).
Oh, that <h:panelGrid> around the <ui:repeat><li> doesn't make sense in HTML perspective. Get rid of it and use <ul> instead. See also HTMLDog HTML Beginner tutorial.

commandLink with ui:repeat in composite component

I am trying to use links in a composite component, my links are in a simple array and do not belong to any managed bean.
<composite:interface>
<composite:attribute name="links" required="true" />
</composite:interface>
<composite:implementation>
<ui:param name="linksSplit" value="#{fn:split(cc.attrs.links, ',')}" />
<ui:repeat var="link" value="#{linksSplit}" >
<h:commandLink value="#{option}" action="#{link}" />
</ui:repeat>
</composite:implementation>
I am getting the following error :
Identity '#{link}' does not reference a MethodExpression instance, returned type: java.lang.String
We are supposed to use String or bean methods in EL expression but I don't understand why we cannot evaluate a parameter which is a String (link in my case).
If I put a real String referenced in my faces-config, it works
<h:commandLink value="#{option}" action="#navigate" />
If you have an explanation or a workaround to get my link working, it would be great
When specifying an EL expression in <h:commandLink action>, it's interpreted as a method expression returning a String (or void if you don't want to navigate). See also the tag documentation:
Name action
Type javax.el.MethodExpression
(signature must match java.lang.Object action())
Description MethodExpression representing the application action to invoke when this component is activated by the user. The expression must evaluate to a public method that takes no parameters, and returns an Object (the toString() of which is called to derive the logical outcome) which is passed to the NavigationHandler for this application.
Given the fact that you seem to want pure page-to-page navigation links, you're actually going in the wrong direction as to using <h:commandLink> for that. You should instead be using <h:link> for that. It generates SEO-friendly and bookmarkable GET links instead of a piece of JavaScript which submits a parent POST form.
<ui:repeat var="link" value="#{linksSplit}" >
<h:link value="#{option}" outcome="#{link}" />
</ui:repeat>
See also:
When should I use h:outputLink instead of h:commandLink?
How to navigate in JSF? How to make URL reflect current page (and not previous one)
Note that this all has nothing to do with composite components. You'd have had exactly the same problem when using this in a normal page.

JSF: Bean method call with parameter

I can't get method calls with parameters to work in JSF 2.0 (MyFaces) and Tomcat 6.
This is how I try it:
<f:selectItems var="item" value="#{bla.someList}
itemValue="#{item.value1}"
itemLabel="#{item.value2}">
<f:param name="param1" value="0" />
</f:selectItems>
I can't define the method like this, right? And why not?
getSomeList(int a)
So this is what I tried:
getSomeList() {
Integer a = Integer.parseInt(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("param1"));
return doSomething(a);
}
And this is what I get:
java.lang.NumberFormatException: null
java.lang.Integer.parseInt(Integer.java:417)
I would be very grateful if someone helped me out. Thanks!
UPDATE: Ah, it worked with #{bla.getSomeList(0)}!
I can't define the method like this, right?
getSomeList(int a)
No.
And why not?
Because you're using old Tomcat 6 which doesn't support EL 2.2 where this feature was introduced.
And this is what I get:
java.lang.NumberFormatException: null
java.lang.Integer.parseInt(Integer.java:417)
Because there it is null. The <f:param> works in links/buttons only, not on plain components.
In order to get method calls in EL to work, you need to upgrade to a Servlet 3.0 / EL 2.2 capable container like Tomcat 7, or to replace Tomcat 6's default EL 2.1 implementation by one which supports parameterized method calls. For detail see this answer. Once done that, you can use
<f:selectItems value="#{bla.getSomeList(0)}" ... />
An alternative is to replace List by Map, which can be a custom implementation which does (lazy) loading on get() method.
public Map<String, List<Something>> getSomeMap() {
return someCustomLazyLoadingMap;
}
with
<f:selectItems value="#{bla.someMap.keyName}" ... />
Try using
<f:selectItems var="item" value="#{bla.someList(0)} itemValue="#{item.value1}" itemLabel="#{item.value2}"/>
This works for some implementations of JSF.

Resources