jsf working with collection/map - jsf

Can I bind my h:dataTable/rich:dataTable with some Map? I found that h:dataTable can work only with List object and deleting in List can be very heavy.

If you want to have only one method in your backing bean that provides the map, you can do something like this:
class Bean {
public Map<T,U> getMap() {
return yourMap;
}
}
and use this in your JSF view
<h:dataTable value="#{bean.map.keySet().toArray()}" var="key">
<h:outputText value="#{bean.map[key]}"/>
</h:dataTable>
This converts the key set into an array, which can be iterated by the datatable. Using the "()"-expression requires Unified Expression Language 2 (Java EE 6).

Yes, that's right. dataTable, ui:repeat and friends only work with Lists.
You can just add a managed bean method that puts map.keySet() or map.values() into a list depending on which you want to iterate over.
Typically when I want to iterate a map from a JSF view, I do something like
<h:dataTable value="#{bean.mapKeys}" var="key">
<h:outputText value="#{bean.map[key]}"/>
</h:dataTable>
with managed bean property
class Bean {
public List<T> mapKeys() {
return new ArrayList<T>(map.keySet());
}
}
or something like that.
Of course, this makes the most sense if you're using something like TreeMap or LinkedHashMap that preserves ordering.

Related

h:selectBooleanCheckbox is not passing the result to a Map

I want to pass check boxes to a backing CDI-Bean. The postTest.values are just a List of Longs.
<h:form>
<h:dataTable value="#{postTest.values}" var="val">
<h:column>
<h:outputLabel value="#{val}"/>
</h:column>
<h:column>
<h:selectBooleanCheckbox value="#{postTest.checked[val]}"/>
</h:column>
</h:dataTable>
<h:commandButton action="#{postTest.process}"/>
</h:form>
The action method should print out the checked values. But it is just empty.
#Named
#RequestScoped
public class PostTest {
List<Long> values;
Map<Long, Boolean> checked;
...
public String process() {
logger.info(this.toString() + "Processing");
for (Long l : checked.keySet()) {
logger.info(this.toString() + "\t" + l + ". checked: " + checked.get(l));
}
return "index2";
}
...
}
When I add logging to the getChecked() method, I can see, that it is just retrieved once per column and its content isn't changed at all.
The problem seem to be related to the point that the postTest.values is not initialized when the form passes the values. Because if I initialize the postTest.values in the constructor (or a #PostConstruct) the checked items are passed correctly.
Why do I need to initialize the postTest.values at all after the POST request is executed?
Is there a way to prevent that?
Or do I have another option? E.g. make sure that the postTest.values are initialized properly not using the constructor nor the #PostConstruct, cause I want to pass values to it before initialization (I tried listeners, but they don't seem to solve that).
Thanks!
Tim
You can also use Myfaces CODI #ViewAccessScoped annotation if you don't want to play with #ConversationScoped and the start() and end() methods. it is a CDI extension that is kind of equivalent to #ViewScoped of JSF managed bean. I did not check the implementation of this annotation but I see many developers tell that it is even better than #ViewScoped annotation.
Just download Myfaces CODI and drop it in your classpath and use the annotation.

How to display elements of ArrayList by index in EL expression in JSF page

I want to display java arraylist into JSF page. I generated arraylist from database. Now I want to display the list into JSF page by calling the list elements index by index number. Is it possible to pass a parameter to bean method from an EL expression in JSF page directly and display it?
You can access a list element by a specific index using the brace notation [].
#ManagedBean
#RequestScoped
public class Bean {
private List<String> list;
#PostConstruct
public void init() {
list = Arrays.asList("one", "two", "three");
}
public List<String> getList() {
return list;
}
}
#{bean.list[0]}
<br />
#{bean.list[1]}
<br />
#{bean.list[2]}
As to parameter passing, surely it's possible. EL 2.2 (or JBoss EL when you're still on EL 2.1) supports calling bean methods with arguments.
#{bean.doSomething(foo, bar)}
See also:
Our EL wiki page
Invoke direct methods or methods with arguments / variables / parameters in EL
I however wonder if it isn't easier to just use a component which iterates over all elements of the list, such as <ui:repeat> or <h:dataTable>, so that you don't need to know the size beforehand nor to get every individual item by index. E.g.
<ui:repeat value="#{bean.list}" var="item">
#{item}<br/>
</ui:repeat>
or
<h:dataTable value="#{bean.list}" var="item">
<h:column>#{item}</h:column>
</h:dataTable>
See also:
How iterate over List<T> and render each item in JSF Facelets

Getting same instance of `componentType` in composite component on every use

Hi Have this Wierd Issue in which I am using a Composite Component which I wrote and I get values from the previous use of the backing bean of the CC (the componentType bean)
I don't know how to describe this better than just show the code.
I'll try to be brief about it and cut the redundant parts:
This is the Composite Component definition:
<cc:interface componentType="dynamicFieldGroupList">
<cc:attribute name="coupletClass" />
<cc:attribute name="form" default="#form"/>
<cc:attribute name="list" type="java.util.List" required="true"/>
<cc:attribute name="fieldNames" type="java.util.List" required="true" />
</cc:interface>
<cc:implementation>
<h:dataTable value="#{cc.model}" var="currLine">
<h:column>
<h:outputText id="inner_control_component" value="Inner Look at currLine:#{currLine}"/>
</h:column>
</h:dataTable>
</cc:implementation>
The CC bean defintion:
#FacesComponent(value = "dynamicFieldGroupList")
// To be specified in componentType attribute.
#SuppressWarnings({ "rawtypes", "unchecked" })
// We don't care about the actual model item type anyway.
public class DynamicFieldGroupList extends UIComponentBase implements
NamingContainer
{
private transient DataModel model;
#Override
public String getFamily()
{
return "javax.faces.NamingContainer"; // Important! Required for
// composite components.
}
public DataModel getModel()
{
if (model == null)
{
model = new ListDataModel(getList());
}
return model;
}
private List<Map<String, String>> getList()
{ // Don't make this method public! Ends otherwise in an infinite loop
// calling itself everytime.
return (List) getAttributes().get("list");
}
}
And the use code:
<ui:repeat var="group" value="#{currentContact.detailGroups}">
<h:panelGroup rendered="#{not empty group.values}">
<h:outputText id="controlMsg" value=" list:#{group.values}" /><br/><br/>
<utils:fieldTypeGroupList list="#{group.values}"
fieldNames="#{group.fields}" coupletClass="utils" />
</h:panelGroup>
</ui:repeat>
The text of id controlMsg displays the correct values in #{group.values} while the control output inside the component of id inner_control_component shows the values from the previous use.
The values are correct the first time...
I guess it's a fundemental error in use of a CC bean, otherwise it could be a bug with MyFaces 2.1 (Which I'm using)
The explanation for this behaviour is simple: there's only one component definied in the view. So there's also only one backing component with one model. Since the model is lazily loaded on first get, the same model is been reused in every iteration of a parent iterating component.
The <ui:repeat> doesn't run during view build time (as JSTL does), but during view render time. So there are physically not as many components in the view as items which are iterated by <ui:repeat>. If you were using <c:forEach> (or any other iteration tag which runs during view build time), then the composite component would have behaved as you'd expect.
You would like to change the way how the datamodel is kept in the backing component. You would like to preserve a separate datamodel for each iteration of a parent iterating component. One of the ways is to replace the model property as follows:
private Map<String, DataModel> models = new HashMap<String, DataModel>();
public DataModel getModel() {
DataModel model = models.get(getClientId());
if (model == null) {
model = models.put(getClientId(), new ListDataModel(getList()));
}
return model;
}
See also:
What's the view build time?
The problem described here is an old known isse in JSF, hidden by the usage of composite components. It is so important and so difficult, that instead answer here I create a detailed answer in a blog entry for this one: JSF component state per row for datatables
To keep this answer short, I'll say to you it is not a bug in MyFaces 2.1. Please use 2.1.1, because that is a quick bug fix version of 2.1.0. In JSF 2.1 there is a new property for h:dataTable called rowStatePreserved, and this scenario is just one case where "this little baby" becomes useful. Just replace ui:repeat with h:dataTable and add rowStatePreserved="true". That will do the trick. If you need to manipulate the model (add or remove rows) you can use tomahawk t:dataTable and t:dataList, but you will have to take an snapshot version for now. Note this is new stuff not available in any different JSF framework an the moment (JUN 2011).
If you need more info, keep tuned with MyFaces Team on Twitter or ask to the experts on MyFaces Users and Dev Mailing Lists.

Display key and value of HashMap entries in JSF page

I would like to display HashMap keys and its associated value in the JSF UI.
How can I achieve this? How can I iterate over a HashMap in JSF page using some iterator component like <h:datatable>?
Only <c:forEach> supports Map. Each iteration gives a Map.Entry instance back (like as in a normal Java for loop).
<c:forEach items="#{yourBean.map}" var="entry">
<li>Key: #{entry.key}, value: #{entry.value}</li>
</c:forEach>
The <h:dataTable> (and <ui:repeat>) only supports List (JSF 2.2 will come with Collection support). You could copy all keys in a separate List and then iterate over it instead and then use the iterated key to get the associated value using [] in EL.
private Map<String, String> map;
private List<String> keyList;
public void someMethodWhereMapIsCreated() {
map = createItSomeHow();
keyList = new ArrayList<String>(map.keySet());
}
public Map<String, String> getMap(){
return map;
}
public List<String> getKeyList(){
return keyList;
}
<h:dataTable value="#{yourBean.keyList}" var="key">
<h:column>
Key: #{key}
</h:column>
<h:column>
Value: #{yourBean.map[key]}
</h:column>
</h:dataTable>
Noted should be that a HashMap is by nature unordered. If you would like to maintain insertion order, like as with List, rather use LinkedHashMap instead.
With <ui:repeat> (JSF 2.2 and onwards):
<ui:repeat var="entry" value="#{map.entrySet().toArray()}">
key:#{entry.key}, Id: #{entry.value.id}
</ui:repeat>
Source: https://gist.github.com/zhangsida/9206849

JSF: How to bind many of h:selectBooleanCheckbox?

I have a problem to bind list of h:selectBooleanCheckbox to my bean.
Anybody helps ?
This is not working:
<ui:repeat value="#{cartBean.productsList}" var="cartProduct" varStatus="i">
<h:selectBooleanCheckbox binding="#{cartBean.checkboxes[i.index]}" />
</ui:repeat>
public class CartBean extends BaseBean {
public List<Product> getProductsList() {...}
private HtmlSelectBooleanCheckbox[] checkboxes;
public HtmlSelectBooleanCheckbox[] getCheckboxes() {
return checkboxes;
}
public void setCheckboxes(HtmlSelectBooleanCheckbox[] checkboxes) {
this.checkboxes = checkboxes;
}
}
I get error:
javax.faces.FacesException: javax.el.PropertyNotFoundException: /WEB-INF/flows/main/cart.xhtml #26,97 binding="#{cartBean.checkboxes[i.index]}": Target Unreachable, 'checkboxes' returned null
I solved my problem. I used code like below and get what i want (thanks to BalusC blog - http://balusc.blogspot.com/2006/06/using-datatables.html#SelectMultipleRows):
<ui:repeat value="#{cartBean.productsList}" var="cartProduct" varStatus="i">
<h:selectBooleanCheckbox value="#{cartBean.selectedIds[cartProduct.id]}" />
</ui:repeat>
public class CartBean extends BaseBean {
private Map<Integer, Boolean> selectedIds = new HashMap<Integer, Boolean>();
public Map<Integer, Boolean> getSelectedIds() {
return selectedIds;
}
}
Your concrete problem is caused because the binding attribute is evaluated during view build time, that moment when the XHTML source code is turned into a JSF UI component tree, while the <ui:repeat> runs during view render time, that moment when the JSF UI component tree needs to produce HTML.
In other words, the #{i.index} is only available during view render time and evaluates as null during view build time. In effects, you're doing a binding="#{cartBean.checkboxes[null]}"
There's another conceptual mistake here: you seem to expect that the <ui:repeat> produces physically multiple <h:selectBooleanCheckbox> components. This is untrue. There's physically only one <h:selectBooleanCheckbox> which is reused multiple times to produce HTML based on the currently iterated variable. Actually, binding="#{cartBean.checkbox}" was been sufficient. However, collecting the values is a story apart. I won't go in detail, but you can find several hints in this answer: Validate order of items inside ui:repeat.
In order to achieve the (apparent) concrete functional requirement of generating physically multiple <h:selectBooleanCheckbox> components and binding each to a separate array item, you should be using an iteration component which runs during view build time instead of view render time. That's the JSTL <c:forEach>:
<c:forEach items="#{cartBean.productsList}" var="cartProduct" varStatus="i">
<h:selectBooleanCheckbox binding="#{cartBean.checkboxes[i.index]}" />
</c:forEach>
But, after all, using binding on a bean property should be avoided as much as possible. Use instead exactly that attribute which you ultimately need: the value attribute. This way you don't need to do a HtmlSelectBooleanCheckbox#getValue() everytime. You already figured the right solution with a Map<Integer, Boolean> selectedIds:
<ui:repeat value="#{cartBean.productsList}" var="cartProduct">
<h:selectBooleanCheckbox value="#{cartBean.selectedIds[cartProduct.id]}" />
</ui:repeat>
See also:
JSTL in JSF2 Facelets... makes sense?
I don't know if you can bind elements stored in an array. But in your code, the problem is that your HtmlSelectBooleanCheckbox[] is null. So maybe change your Java code to:
public HtmlSelectBooleanCheckbox[] getCheckboxes() {
if (checkboxes == null) {
checkboxes = new HtmlSelectBooleanCheckbox[getProductsList().size()];
}
return checkboxes;
}
but I am really not sure if it will work... Maybe the solution is to not bind your HtmlSelectBooleanCheckbox elements in the Java code. Why do you need to bind them?

Resources