JSF/SEAM: How to pre-select checkboxes in a form - java

I have a form where i have to preselect some checkboxes. How is that possible with jsf/seam? In plain html you would just add the "checked" (or checked="checked") as attribute to the checkboxes. But with f:selectItems I have no clue...also the Object "SelectItem" does not provide any setter for this...

You need to preset them in the property behind the component's value attribute as you usually do for every UIInput component. You can do that in the bean's constructor or initialization block.
Here's a basic example:
<h:selectManyCheckbox value="#{bean.selectedItems}">
<f:selectItems value="#{bean.selectItems}" />
</h:selectManyCheckbox>
Bean:
private List<String> selectedItems; // +getter +setter.
private List<SelectItem> selectItems; // +getter.
public Bean() {
// Preset the selected items.
this.selectedItems = new ArrayList<String>();
this.selectedItems.add("valueToBePreselected1");
this.selectedItems.add("valueToBePreselected2");
// Those values should be exactly the same as one of the SelectItem values.
// I.e. the Object#equals() must return true for any of them.
}

Populate the property you use in "value" before rendereing the page (for example using a phase listener)
<h:selectManyCheckbox value="#{selectManyCheckBoxBean.selectedItems}">
<f:selectItem itemLabel="India" itemValue="India" />
<f:selectItem itemLabel="China" itemValue="China" />
<f:selectItem itemLabel="Germany" itemValue="Germany" />
<f:selectItem itemLabel="USA" itemValue="USA" />
</h:selectManyCheckbox>

Related

selectItems from PrimeFaces simply won't work

I'm trying to a populate a selectItems from a query and It simply won't WORK. I've tried with List list, List list, Map<Long,String> list... None of then works... There's no error, the prime faces won't show the list. Simply as that.
<p:selectOneMenu id="pessoa" value="#{matriculaController.pessoa}">
<f:selectItem itemLabel="Selecione uma Pessoa" itemValue="" />
<f:selectItems
value="#{selectOneMenuView.pessoaLista}"
var="pessoa"
itemLabel="#{pessoa.nome}"
itemValue="#"
/>
</p:selectOneMenu>
Controller:
#Getter
#Setter
#Autowired
private List<Person> pessoaLista;
public void findAllPersons() {
pessoaLista = matriculaService.carregarPessoas();
}
My query function is working, the pessoaLista is populated, the HTML doesn't break. It simply comes blank.
And I've copied from the PrimeFaces docs... (docs)
Use List<Person> and add itemValue="#{pessoa.id}" to your <f:selectItems>
<p:selectOneMenu id="pessoa"
value="#{matriculaController.pessoa}">
<f:selectItem itemLabel="Selecione uma Pessoa"
itemValue="" />
<f:selectItems value="#{selectOneMenuView.pessoaLista}"
var="pessoa"
itemLabel="#{pessoa.nome}"
itemValue="#{pessoa.id}"/>
</p:selectOneMenu>

Binding radio buttons to specific enum values in Spring Webflow

In my Spring Webflow (with JSP views) I have a model that contains an enum for one of its fields. I need a form with a set of radio buttons that contain only a couple of those possible enum values and I can't seem to crack how to do it.
So my flow is something like this:
<on-start>
<evaluate expression="someService.getModel()" result="flowScope.myModel" />
</on-start>
<view-state id="step1" view="step1View" model="myModel">
<transition on="proceed" to="step2"/>
</view-state>
And myModel has a field called "paymentType" which is an enum (called PaymentType) that could look soemthing like this:
public enum PaymentType{
RE("A paper reciept"),
CC("Credit Card"),
PA("Pre-Authorised Debit"),
MC("MyCoin"),
private final String shortDescription;
PaymentOptionType(final String shortDescription) {
this.shortDescription = shortDescription;
}
public String getShortDescription() {
return shortDescription;
}
}
So let's say in my step1 page I only want to put 2 of these values on the form.
So it would look like:
* A paper reciept
* MyCoin
|Submit|
And it would bind the selected value to the paymentType field in the model.
So I'm wondering how to populate the radio buttons in my form in step1.jsp
<form:form id="paymentForm" name="paymentForm" modelAttribute="myModel" method="post" action="${flowExecutionUrl}">
<!-- What to put for radio buttons here? -->
<button name="_eventId_proceed">Next Step</button>
</form:form>
try:
<form:radiobutton path="paymentType" value="RE"/>A paper receipt
<form:radiobutton path="paymentType" value="MC"/>My Coin
..
or add something like this to your flow
<on-start>
<evaluate expression="someService.getPaymentTypes()" result="flowScope.paymentTypes" />
</on-start>
and then use
<c:forEach var="paymentType" items="${paymentTypes}>
<form:radiobutton path="paymentType" value="${paymentType}"/>${paymentType.shortDescription}
</c:forEach>

Dependent p:selectOneMenu Population of values

I am using JSF 2.0 with Primefaces 3.4.2
I have two p:selectOneMenu, first one parent and second child, based on parent value, child component gets populated.
Parent p:selectOneMenu
<p:selectOneMenu id="empl" value="#{empMB.employee}">
<f:selectItems value="#{empMB.employeeList}" var="emp"
itemLabel="#{emp.employeeName}" itemValue="#{emp.employeeNumber}"/>
<p:ajax update="department" />
</p:selectOneMenu>
Child p:selectOneMenu
<p:selectOneMenu id="department" value="#{deptMB.department}">
<f:selectItems value="#{deptMB.loadDepartments(<??>)}" var="dept"
itemLabel="#{dept.departmentName}" itemValue="#{dept.departmentCode}"/>
</p:selectOneMenu>
I have a method in department ManagedBean called loadDepartments with one argument
public void loadDepartments(String employeeNumber)
How can I pass value to loadDepartments in child component so that it will load all the departments based on the code selected in parent component?
If I am substituting #{deptMB.loadDepartments(empMB.employee.employeeCode)} I am getting
Error Parsing: #{deptMB.loadDepartments({empMB.employee.employeeCode})}
Any help is highly appreciable?
I'd do this:
Add a list variable to your bean (and the appropriate getter): this list will hold the values for the child combo box;
Add a listener to the p:ajax call on the parent combo box: the listener populates the list of child values (you'll have access to the selected parent item inside its listener); and
Update your xhtml to use the values from the list created on step 1 instead of the loadDepartments method you're trying to invoke.
This is normally how I do this sort of thing and it should work out for you.
EDIT
Code for the page:
<p:selectOneMenu id="empl" value="#{empMB.employee}" converter="#{employeeConverter}">
<f:selectItems value="#{empMB.employeeList}" var="emp" itemLabel="#{emp.employeeName}" itemValue="#{emp.employeeNumber}"/>
<p:ajax update="department" listener="#{empMB.onEmployeeSelect}" process="#this"/>
</p:selectOneMenu>
<p:selectOneMenu id="department" value="#{deptMB.department}" converter="#{departmentConverter}">
<f:selectItems value="#{empMB.departmentList}" var="dept" itemLabel="#{dept.departmentName}" itemValue="#{dept.departmentCode}"/>
</p:selectOneMenu>
Snippet for the bean:
public class EmpMB{
...
private List<Department> departmentList;
private Employee employee;
public List getDepartmentList(){
return departmentList;
}
public void onEmployeeSelect(){
departmentList = someService.getDepartmentsForEmployee(employee);
}
...
}
Converter sample (note that it's a spring component so that I can inject my service layer into it, but you don't HAVE to do it this way):
#Component("employeeConverter")
public class EmployeeConverter implements Converter {
#Override
public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2) {
//TODO: implement this
}
#Override
public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2) {
//TODO: implement this
}
}

How can i get value from <h:selectManyCheckbox>

I have one collection , which I'm displaying in my .xhtml page by <h:dataTable>. I want to reach a few goals: at first I want to set list.check value by <h:selectManyCheckbox>, at second I want whatever the values remains selected until the end of current session. Now It displays correctly, but when I select some value it doesn't transmit it in list.check property. I'm using JSF v.2.2.
Code in JSF bean:
private List<AnswerDTO> answerListDto;
//getters and setters
Code in .xhtml
<h:form>
<h:dataTable value="#{main.answerListDto}" var="list">
<h:column>
<h:selectManyCheckbox value="#{list.check}">
<f:selectItem itemValue="1" itemLabel="#{list.ansValue}" />
</h:selectManyCheckbox>
</h:column>
</h:dataTable>
</h:form>
AnswerDTO class:
public class AnswerDTO implements Serializable, DTO {
private static final long serialVersionUID = 1L;
private Integer id;
private Question questId;
private String ansValue;
private String ansStatus;
private String check;
//getters and setters
}
Strange use of selectManyCheckbox I must say. Concrete problem is that value of selectManyCheckbox must be an array.
My opinion is that selectBooleanCheckbox should be used instead of selectManyCheckbox. Your check property can have only two values, an empty array (if checkbox is not selected), and array of length 1 with value which is equal to ansValue (if checkbox is selected).

JSF - UISelectItems problem

Strange error i received from compiler:
Expected a child component type of UISelectItem/UISelectItems for component type javax.faces.SelectOne(siachoice). Found javax.faces.component.UISelectItems.
So, if he was expecting UISelectItems, and found UISelectItems, then where is the error?
My JSP implementation:
<h:selectOneMenu id="siachoice" value="#{dbSelectBean.currentOption}">
<f:selectItems value="#{dbSelectBean.dbs}" />
</h:selectOneMenu>
Method, where i am setting UISelectItem to UISelectItems:
private UISelectItems populateDatabases(String databaseString) {
UISelectItems selects = new UISelectItems();
List<UISelectItem> result = new ArrayList<UISelectItem>();
StringTokenizer tokeniz = new StringTokenizer(databaseString, GlobalConstants.DELIMITER);
while(tokeniz.hasMoreTokens()){
String tempDB = tokeniz.nextToken();
UISelectItem item = new UISelectItem();
item.setItemValue(tempDB);
item.setItemLabel(tempDB);
result.add(item);
}
selects.setValue(result);
return selects;
}
Then, of course, i am setting it to the bean variable dbs.
Help?
You must return a Collection of javax.faces.model.SelectItem
List list = new ArrayList();
list.add(new SelectItem(value, label));
return list;
The <f:selectItems value="#{bean.items}" /> expects one of the following values:
public SelectItem[] getItems() {}
public List<SelectItem> getItems() {}
public Map<String, Object> getItems() {}
The commonly used one is indeed the List<SelectItem>.
Edit: as response to the comment: UISelectItem represents the <f:selectItem> component. The same applies to UISelectItems and <f:selectItems>. E.g.
<f:selectItem binding="#{bean.selectItem}" />
<f:selectItems binding="#{bean.selectItems}" />
which are bound as
private UISelectItem selectItem;
private UISelectItems selectItems;
// +getter +setter
this way you can control the components programmatically -as for every other UIComponent.
<h:form>
<h:selectOneListbox size="5" >
<f:selectItems value="#{userManager.Test()}" />
</h:selectOneListbox>
</h:form>
import javax.faces.model.SelectItem;
import tn.com.ttnproject.entity.*;
#Name("userManager")
#Scope(ScopeType.CONVERSATION)
public class UserManager {
public List <SelectItem> listAllUsersNames;
SelectItem element;
public List<SelectItem> Test(){
listAllUsersNames = new ArrayList<SelectItem>();
for (int i=1;i<=10;i++)
{
element=new SelectItem(
new Integer(i),
i+".00 euros",
"Produit à "+i+".00 euros");
listAllUsersNames.add(element);
}
return listAllUsersNames;
}
}
The problem is UISelectItem is a component clas so it has to be paired with jsf tag by binding attribute. If you want to have pure values you have to use SelectItem(s) classes.

Categories

Resources