I'm trying to solve some problems here with JSF but I'm having no luck. I will try to resume my code, because I don't think a lot of code here can help you solve me this problem, so I will try to describe better my problem.
Now I have a String that stores three shifts: matutinal, vespertine and nightly. In my architecture I need that myStringArray[0] = 'matutinal'
, myStringArray[1] = 'vespertine'
and myStringArray[3] = 'nightly'
.
I'm using JSF 2.0 and Primefaces in my application - some of omnifaces too.
Following is my JSF code:
<p:selectManyCheckbox value="#{escolaMBean.turnos}">
<f:selectItems value="#{escolaMBean.listaTodosTurnos}" var="turno" itemValue="#{turno.nome}" itemLabel="#{turno.nome}" />
</p:selectManyCheckbox>
Note in escolaMBean:
// Stores the selected "Turnos" (This means "shift" in English)
String[] turnos = new String[3];
// Stores all the "Turnos" received from DB
ArrayList<Turno> listaTodosTurnos = <myControl.myDbRequest()>
/*
* Turno have a simple ID and Name, in DB we have 3 "Turnos": Matutinal, Vespertine, Nightly
* In this MBean I have all getters and setters - and in "Turno" class too.
* When I set one string in turnos[n], this set the right value
*/
So, based on these things, how can I select turnos[0] if matutinal checkbox is selected, turnos1 if vespertine checkbox is selected and turnos[2] if nightly checkbox is selected? Now this don't works, because if I select Nightly first, the position turnos[0] will be equals to "nigthly".
How can I solve this problems?
What you want is not possible by standard JSF means. You're limited by the way how HTML works. The HTML <input type="checkbox">
only submits information about selected values, not about unselected values. JSF is here merely the messenger between HTML/HTTP and the Javabean model. All JSF retrieves is a collection of selected values. It doesn't retrieve a collection of unselected values.
You need to intersect the unselected values from the available values based on the selected values yourself.
Here's a kickoff example, assuming that you've a
private List<String> selectedItems; // <p:selectManyCheckbox value>
private List<Item> availableItems; // <f:selectItems value>
private String[] orderedSelectedItems; // Selected items ordered by index
then this should do, in for example an action listener after submitting the form:
orderedSelectedItems = new String[availableItems.size()];
int i = 0;
for (Item item : availableItems) {
String name = item.getName();
orderedSelectedItems[i++] = selectedItems.contains(name) ? name : null;
}