rich:autocomplete - is it desperately missing itemValue= ?
healeyb Feb 21, 2012 9:30 AMI'm really having problems getting rich:autocomplete to work with what I consider a typical use case.
I think part of the problem is that I can't find an example, whether in the showcase or in the practical
richfaces 2 book, where the value selected by the user is used in any way. Nowhere will you find the
value= attribute used, or the selected item used in any other way (i.e. in a value change listener).
The basic problem is that everything seems to have been thought about, except storing a reference to
what you've selected. A familiar scenario is using f:selectItems like this:
@Entity
public class Team {
@Id
long id;
String name;
}
...
public Team selectedTeam;
public List<Team> teamList = new ArrayList<>();
...
teamList.add(new Team(1, "Liverpool"));
teamList.add(new Team(2, "Chelsea"));
teamList.add(new Team(2, "Manchester United"));
...
<h:selectOneMenu value="#{bean.selectedTeam}" converter="genericConverter">
<f:selectItems value="#{bean.teamList}" var="var" itemLabel="#{var.name}" itemValue="#{var}"/>
</h:selectOneMenu>
You have a List<Team>, selectItems displays the itemLabel, in this case the team name, and on
selection you store a reference to the Team object in selectedTeam. If you wanted to you could
easily store the primary key id instead. All pretty straightforward although a converter is required.
A rich:autocomplete version of the above example could look like this:
rich:autocomplete value="#{bean.selectedTeam}"
mode="cachedAjax"
layout="table"
var="var"
fetchValue="#{var.name}"
autocompleteMethod="#{bean.teamSearch}">
<rich:column>
<h:outputText value="#{var.name}"/>
</rich:column>
<a4j:ajax event="selectitem"/>
</rich:autocomplete
the teamSearch() method returns a List<Team> where the characters typed into autocomplete
input match in some way the team name. If I type in "Liver" we get one row returned. What is
supposed to happen is that the value of fetchValue="#{var.name}" replaces any characters typed
into the input, so "Liverpool". But fetchValue is also used for the value attribute, so we'll get a
ClassCastException trying to cast a String to a Team (selectedTeam).
If you add a converter, the getAsObject method will be called with fetchValue (the name) as the
third parameter, which is probably not what you want.
So the problem is that you want to internally reference the object by the primary key, but display
friendly text to the user, but this seems impossible with the current offering.
Just adding the itemValue attribute would solve the immediate problem, so that there's a difference
between the text displayed in the input box when you make a selection (fetchValue), and the
component value (itemValue).
Any thoughts? I've got to say this is totally unusable for me right now, unless I've missed something
really obvious.
Regards,
Brendan.