JSF greater than zero validator - jsf

How do you create a validator in JSF that validates the input text if it is greater than zero?
<h:inputText id="percentage" value="#{lab.percentage}">
<f:validateDoubleRange minimum="0.000000001"/>
</h:inputText>
I have the code above but I am not sure if this is optimal. Although it works but if another number lesser than this is needed then I need to change the jsf file again.
The use case is that anything that is greater than zero is okay but not negative number.
Any thoughts?

Just create a custom validator, i.e. a class implementing javax.faces.validator.Validator, and annotate it with #FacesValidator("positiveNumberValidator").
Implement the validate() method like this:
#Override
public void validate(FacesContext context, UIComponent component,
Object value) throws ValidatorException {
try {
if (new BigDecimal(value.toString()).signum() < 1) {
FacesMessage msg = new FacesMessage("Validation failed.",
"Number must be strictly positive");
msg.setSeverity(FacesMessage.SEVERITY_ERROR);
throw new ValidatorException(msg);
}
} catch (NumberFormatException ex) {
FacesMessage msg = new FacesMessage("Validation failed.", "Not a number");
msg.setSeverity(FacesMessage.SEVERITY_ERROR);
throw new ValidatorException(msg);
}
}
And use it in the facelets page like this:
<h:inputText id="percentage" value="#{lab.percentage}">
<f:validator validatorId="positiveNumberValidator" />
</h:inputText>
Useful link: http://www.mkyong.com/jsf2/custom-validator-in-jsf-2-0/

Related

JSF Validation Error: Value is not valid

I am having trouble to find my fault when recieving the Error "Validation Error: Value is not valid". After submitting a form, im getting this error, even though, when debugging, the selected Component is the right one. The converter seems to be working fine too thats why I am having a really tough time here. Here is what I have tried so far:
Change #RequestScoped to #ManagedBean and #ViewScoped - Made the SelectOneMenue beofore crash everytime because of a NullpointerException, this did never happen with #RequestScoped, so I am not sure what is happening there...
I double checked the Converter for this SelectedOneMenue, it seems to be working, I made a lot of debugging there, the Object that was converted to a String is, at least visible for me, the same that is later converted back from String to the Object.
The equals() Method: The equals Method seems OK to me, it literally just checks if the .id is the same, when checking this at the converter, it is always right. Maybe I'd rather search here for the error, even though I cant figure out what could be possibly wrong here.
Here are the parts of my code that I guess will be interesting for you, I have already made quite some research, I found quite good stuff though I couldn't get this to work but this must not mean anything since I just started programming with JavaEE and JSF ( + Primefaces).
Component equals() Method
#Override
public boolean equals(Object obj) {
if(obj == null){
//System.out.println("Component is NULL in equals() method");
}
if(this.id == ((Component) obj).id) {
return true;
}else {
return false;
}
}
Component Converter Class
#ManagedBean(name = "componentConverterBean")
#FacesConverter (value = "componentConverter")
public class ComponentConverter implements Converter{
#PersistenceContext(unitName="PU")
private EntityManager em;
#Override
public String getAsString(FacesContext context, UIComponent component, Object modelValue) {
if (modelValue == null) {
return "";
}
return modelValue.toString();
}
#Override
public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) {
if (submittedValue == null || submittedValue.isEmpty()) {
System.out.println("ComponentConverter: submittedValue is null");
return null;
}
try {
System.out.println("ComponentConverter: Value to be found: " + submittedValue);
return em.find(Component.class, Integer.parseInt(submittedValue));
} catch (NumberFormatException e) {
throw new ConverterException(new FacesMessage(submittedValue + " is not a valid Component ID", e.getMessage()));
}
}
}
Part of the .xhtml file containing the SelectOneMenues
<p:outputLabel for="facility" value="Facility: " />
<p:selectOneMenu id="facility" value="#{visualization.facility}" converter="#{facilityConverterBean}" style="width:150px">
<p:ajax process="#this" partialSubmit="true" listener="#{visualization.onFacilityChange()}" update="component" />
<f:selectItem itemLabel="Select Facility" noSelectionOption="true" />
<f:selectItems value="#{visualization.facilities}" var="facility" itemLabel="#{facility.name}" itemValue="#{facility}" />
</p:selectOneMenu>
<p:outputLabel for="component" value="Components: " />
<p:selectOneMenu id="component" value="#{visualization.component}" converter="#{componentConverterBean}" style="width:150px">
<f:selectItem itemLabel="Select Component" noSelectionOption="true" />
<f:selectItems value="#{visualization.components}" var="comp" itemLabel="#{comp.name}" itemValue="#{comp}" />
</p:selectOneMenu>
"Components: Überprüfungsfehler: Wert ist ungültig."
This is the exact Error, which translates to:
"Components: Validation error: Value is not valid. "
I am very grateful for any help here. Thanks in advance.
Use a container object instead of an entity for value="#{visualization.component}".
e.g.
class ComponentDto {
private Component componentEntity;
private Component getComponentEntity() {
return this.componentEntity;
}
private void setComponentEntity(Component componentEntity) {
this.componentEntity = componentEntity;
}
}
See also: https://github.com/primefaces/primefaces/issues/2756

Using a "Please select" f:selectItem with null/empty value inside a p:selectOneMenu

I'm populating a <p:selectOneMenu/> from database as follows.
<p:selectOneMenu id="cmbCountry"
value="#{bean.country}"
required="true"
converter="#{countryConverter}">
<f:selectItem itemLabel="Select" itemValue="#{null}"/>
<f:selectItems var="country"
value="#{bean.countries}"
itemLabel="#{country.countryName}"
itemValue="#{country}"/>
<p:ajax update="anotherMenu" listener=/>
</p:selectOneMenu>
<p:message for="cmbCountry"/>
The default selected option, when this page is loaded is,
<f:selectItem itemLabel="Select" itemValue="#{null}"/>
The converter:
#ManagedBean
#ApplicationScoped
public final class CountryConverter implements Converter {
#EJB
private final Service service = null;
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
try {
//Returns the item label of <f:selectItem>
System.out.println("value = " + value);
if (!StringUtils.isNotBlank(value)) {
return null;
} // Makes no difference, if removed.
long parsedValue = Long.parseLong(value);
if (parsedValue <= 0) {
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "", "Message"));
}
Country entity = service.findCountryById(parsedValue);
if (entity == null) {
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_WARN, "", "Message"));
}
return entity;
} catch (NumberFormatException e) {
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "", "Message"), e);
}
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
return value instanceof Country ? ((Country) value).getCountryId().toString() : null;
}
}
When the first item from the menu represented by <f:selectItem> is selected and the form is submitted then, the value obtained in the getAsObject() method is Select which is the label of <f:selectItem> - the first item in the list which is intuitively not expected at all.
When the itemValue attribute of <f:selectItem> is set to an empty string then, it throws java.lang.NumberFormatException: For input string: "" in the getAsObject() method even though the exception is precisely caught and registered for ConverterException.
This somehow seems to work, when the return statement of the getAsString() is changed from
return value instanceof Country?((Country)value).getCountryId().toString():null;
to
return value instanceof Country?((Country)value).getCountryId().toString():"";
null is replaced by an empty string but returning an empty string when the object in question is null, in turn incurs another problem as demonstrated here.
How to make such converters work properly?
Also tried with org.omnifaces.converter.SelectItemsConverter but it made no difference.
When the select item value is null, then JSF won't render <option value>, but only <option>. As consequence, browsers will submit the option's label instead. This is clearly specified in HTML specification (emphasis mine):
value = cdata [CS]
This attribute specifies the initial value of the control. If this attribute is not set, the initial value is set to the contents of the OPTION element.
You can also confirm this by looking at HTTP traffic monitor. You should see the option label being submitted.
You need to set the select item value to an empty string instead. JSF will then render a <option value="">. If you're using a converter, then you should actually be returning an empty string "" from the converter when the value is null. This is also clearly specified in Converter#getAsString() javadoc (emphasis mine):
getAsString
...
Returns: a zero-length String if value is null, otherwise the result of the conversion
So if you use <f:selectItem itemValue="#{null}"> in combination with such a converter, then a <option value=""> will be rendered and the browser will submit just an empty string instead of the option label.
As to dealing with the empty string submitted value (or null), you should actually let your converter delegate this responsibility to the required="true" attribute. So, when the incoming value is null or an empty string, then you should return null immediately. Basically your entity converter should be implemented like follows:
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (value == null) {
return ""; // Required by spec.
}
if (!(value instanceof SomeEntity)) {
throw new ConverterException("Value is not a valid instance of SomeEntity.");
}
Long id = ((SomeEntity) value).getId();
return (id != null) ? id.toString() : "";
}
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if (value == null || value.isEmpty()) {
return null; // Let required="true" do its job on this.
}
if (!Utils.isNumber(value)) {
throw new ConverterException("Value is not a valid ID of SomeEntity.");
}
Long id = Long.valueOf(value);
return someService.find(id);
}
As to your particular problem with this,
but returning an empty string when the object in question is null, in turn incurs another problem as demonstrated here.
As answered over there, this is a bug in Mojarra and bypassed in <o:viewParam> since OmniFaces 1.8. So if you upgrade to at least OmniFaces 1.8.3 and use its <o:viewParam> instead of <f:viewParam>, then you shouldn't be affected anymore by this bug.
The OmniFaces SelectItemsConverter should also work as good in this circumstance. It returns an empty string for null.
If you want to avoid null values for your select component, the most elegant way is to use the noSelectionOption.
When noSelectionOption="true", the converter will not even try to process the value.
Plus, when you combine that with <p:selectOneMenu required="true"> you will get a validation error, when user tries to select that option.
One final touch, you can use the itemDisabled attribute to make it clear to the user that he can't use this option.
<p:selectOneMenu id="cmbCountry"
value="#{bean.country}"
required="true"
converter="#{countryConverter}">
<f:selectItem itemLabel="Select"
noSelectionOption="true"
itemDisabled="true"/>
<f:selectItems var="country"
value="#{bean.countries}"
itemLabel="#{country.countryName}"
itemValue="#{country}"/>
<p:ajax update="anotherMenu" listener=/>
</p:selectOneMenu>
<p:message for="cmbCountry"/>
Now if you do want to be able to set a null value, you can 'cheat' the converter to return a null value, by using
<f:selectItem itemLabel="Select" itemValue="" />
More reading here, here, or here
You're mixing a few things, and it's not fully clear to me what you want to achieve, but let's try
This obviously causes the java.lang.NumberFormatException to be thrown
in its converter.
It's nothing obvious in it. You don't check in converter if value is empty or null String, and you should. In that case the converter should return null.
Why does it render Select (itemLabel) as its value and not an empty
string (itemValue)?
The select must have something selected. If you don't provide empty value, the first element from list would be selected, which is not something that you would expect.
Just fix the converter to work with empty/null strings and let the JSF react to returned null as not allowed value. The conversion is called first, then comes the validation.
I hope that answers your questions.
In addition to incompleteness, this answer was deprecated, since I was using Spring at the time of this post :
I have modified the converter's getAsString() method to return an empty string instead of returning null, when no Country object is found like (in addition to some other changes),
#Controller
#Scope("request")
public final class CountryConverter implements Converter {
#Autowired
private final transient Service service = null;
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
try {
long parsedValue = Long.parseLong(value);
if (parsedValue <= 0) {
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "", "The id cannot be zero or negative."));
}
Country country = service.findCountryById(parsedValue);
if (country == null) {
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_WARN, "", "The supplied id doesn't exist."));
}
return country;
} catch (NumberFormatException e) {
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "", "Conversion error : Incorrect id."), e);
}
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
return value instanceof Country ? ((Country) value).getCountryId().toString() : ""; //<--- Returns an empty string, when no Country is found.
}
}
And <f:selectItem>'s itemValue to accept a null value as follows.
<p:selectOneMenu id="cmbCountry"
value="#{stateManagedBean.selectedItem}"
required="true">
<f:selectItem itemLabel="Select" itemValue="#{null}"/>
<f:selectItems var="country"
converter="#{countryConverter}"
value="#{stateManagedBean.selectedItems}"
itemLabel="#{country.countryName}"
itemValue="${country}"/>
</p:selectOneMenu>
<p:message for="cmbCountry"/>
This generates the following HTML.
<select id="form:cmbCountry_input" name="form:cmbCountry_input">
<option value="" selected="selected">Select</option>
<option value="56">Country1</option>
<option value="55">Country2</option>
</select>
Earlier, the generated HTML looked like,
<select id="form:cmbCountry_input" name="form:cmbCountry_input">
<option selected="selected">Select</option>
<option value="56">Country1</option>
<option value="55">Country2</option>
</select>
Notice the first <option> with no value attribute.
This works as expected bypassing the converter when the first option is selected (even though require is set to false). When itemValue is changed to other than null, then it behaves unpredictably (I don't understand this).
No other items in the list can be selected, if it is set to a non-null value and the item received in the converter is always an empty string (even though another option is selected).
Additionally, when this empty string is parsed to Long in the converter, the ConverterException which is caused after the NumberFormatException is thrown doesn't report the error in the UIViewRoot (at least this should happen). The full exception stacktrace can be seen on the server console instead.
If someone could expose some light on this, I would accept the answer, if it is given.
This is fully working to me :
<p:selectOneMenu id="cmbCountry"
value="#{bean.country}"
required="true"
converter="#{countryConverter}">
<f:selectItem itemLabel="Select"/>
<f:selectItems var="country"
value="#{bean.countries}"
itemLabel="#{country.countryName}"
itemValue="#{country}"/>
<p:ajax update="anotherMenu" listener=/>
</p:selectOneMenu>
The Converter
#Controller
#Scope("request")
public final class CountryConverter implements Converter {
#Autowired
private final transient Service service = null;
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if (value == null || value.trim().equals("")) {
return null;
}
//....
// No change
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
return value == null ? null : value instanceof Country ? ((Country) value).getCountryId().toString() : null;
//**** Returns an empty string, when no Country is found ---> wrong should return null, don't care about the rendering.
}
}
public void limparSelecao(AjaxBehaviorEvent evt) {
Object submittedValue = ((UIInput)evt.getSource()).getSubmittedValue();
if (submittedValue != null) {
getPojo().setTipoCaixa(null);
}
}
<p:selectOneMenu id="tipo"
value="#{cadastroCaixaMonitoramento.pojo.tipoCaixa}"
immediate="true"
required="true"
valueChangeListener="#{cadastroCaixaMonitoramento.selecionarTipoCaixa}">
<f:selectItem itemLabel="Selecione" itemValue="SELECIONE" noSelectionOption="false"/>
<f:selectItems value="#{cadastroCaixaMonitoramento.tiposCaixa}"
var="tipo" itemValue="#{tipo}"
itemLabel="#{tipo.descricao}" />
<p:ajax process="tipo"
update="iten_monitorado"
event="change" listener="#{cadastroCaixaMonitoramento.limparSelecao}" />
</p:selectOneMenu>

How to show multi error message in jsf while validation is in EJB?

Based on the answer from this question, i understand that if there is an error, EJB will throw an exception which will be catch in the backing bean and backing bean will show user an error message based on exception its catch.
My question is, what if theres more than one error? How can i show multiple error message to the user, while the EJB can only throw one exception at a time?
For example, at registration form user will need to input email address, name, password, and re-password, and must not be null. If all the data is valid but the given email address is already exist, EJB will throw EntityExistException and the user will be notified that email address is already registered. What if theres multiple error like password and re-password not match and the name is empty? And i want to show these two error to the user. What exception should EJB throw? What approach i can take to achieve this?
Note: the validation must be in EJB
You shouldn't be doing validation in a backing bean action method, but in a normal Validator.
E.g.
<h:inputText value="#{register.email}" required="true" validator="#{emailValidator}" />
<h:inputSecret binding="#{password}" value="#{register.password}" required="true" />
<h:inputSecret required="true" validator="confirmPasswordValidator">
<f:attribute name="password" value="#{password.value}" />
</h:inputSecret>
...
with the #{emailValidator} being something like this:
#MangedBean
public class EmailValidator implements Validator {
#EJB
private UserService userService;
#Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
if (value == null) {
return; // Let required="true" handle.
}
if (userService.existsEmail((String) value)) {
throw new ValidatorException(Messages.createError("Email already exists"));
}
}
}
Note that the EJB shouldn't throw an exception here. It should only do that when there's a fatal and unrecoverable error such as DB down or wrong table/column definitions.
And the confirmPasswordValidator being something like this
#FacesValidator("confirmPasswordValidator")
public class ConfirmPasswordValidator implements Validator {
#Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
Object password = component.getAttributes().get("password");
if (value == null || password == null) {
return; // Let required="true" handle.
}
if (!password.equals(value)) {
throw new ValidatorException(Messages.createError("Password do not match"));
}
}
}

Is there a way to update component even when JSF fail during Process Validation phase

I have an input text that have required=true attribute, like below
<h:panelGrid columns=2>
<h:panelGroup id="ccm">
<p:inputText id="txtCCMNumber" value="#{setupView.selectedCCM}"
required="true" requiredMessage="Required">
<p:ajax event="blur" listener="#{setupView.handleLooseFocusCCMTextbox()}"
update=":setupForm:ccm :setupForm:ccmMsg"/>
</p:inputText>
<h:outputText value="Duplicated" id="ccmExisted"
styleClass="ui-message-error ui-widget ui-corner-all"
rendered="#{setupView.ccmNameExisted}"/>
<h:graphicImage id="ccmNotExist" url="resources/images/check-icon.png"
rendered="#{setupView.ccmNameUnique}"
width="18"/>
</h:panelGroup>
<p:message for="txtCCMNumber" id="ccmMsg" display="text"/>
</h:panelGrid>
So my requirement is, if the value is empty, then it will display Required, since required=true, it should fail at Process Validation phase. If the value is unique, then display a check image, if duplicated, then display Duplicated text. The problem that I run into is, after I type something and tab away (let say I type something unique), it displays the check image, I then erase the text, and tab away again, now the Required text appear, but so is the check image. My theory is that, at the Process validation phase, it fail due to the value is empty, so at the update component phase, it does not invoke that method handleLooseFocusCCMTextbox() that will set the boolean ccmNameUnique to false. Is there a way to fix this?
NOTE: handleLooseFocusCCMTextbox() just turn the boolean value on and off to display the check image or Duplicated text.
Answered. Create Validator class, take out required=true
public void validate(FacesContext fc, UIComponent uic, Object value)
throws ValidatorException {
FacesContext context = FacesContext.getCurrentInstance();
SetupView setupView = (SetupView) context.getApplication().
evaluateExpressionGet(context, "#{setupView}", SetupView.class);
if (value == null || value.toString().isEmpty()) {
setupView.setCcmNameUnique(false);
FacesMessage message = new FacesMessage();
message.setSeverity(FacesMessage.SEVERITY_ERROR);
message.setSummary("Error");
message.setDetail("Required");
//This will end up in <p:message>
throw new ValidatorException(message);
}
String rootPath = setupView.getRootPath();
File rootFolder = new File(rootPath);
if (rootFolder.exists() && rootFolder.canRead()) {
List<String> folderNames = Arrays.asList(new File(rootPath).list());
if (folderNames.contains(value.toString())) {
setupView.setCcmNameUnique(false);
FacesMessage message = new FacesMessage();
message.setSeverity(FacesMessage.SEVERITY_ERROR);
message.setSummary("Error");
message.setDetail("Duplicate");
//This will end up in <p:message>
throw new ValidatorException(message);
} else {
setupView.setCcmNameUnique(true);
}
} else {
logger.log(Level.SEVERE, "Please check the root folder path as "
+ "we cannot seems to see it. The path is {0}", rootPath);
}
}
You want to use a validator instead of an action listener.
<p:inputText id="txtCCMNumber" value="#{setupView.selectedCCM}"
required="true" requiredMessage="Required"
validator="#{setupView.validateDuplicateCCM}">
<p:ajax event="blur" update="ccm ccmMsg" />
</p:inputText>
with
public void validateDuplicateCCM(FacesContext context, UIComponent component, Object value) throws ValidatorException {
if (value == null || value.toString().isEmpty()) {
return; // Let required="true" handle.
}
// ...
if (duplicate) {
((UIInput) component).setValid(false);
ccmNameExisted = true;
// I'd rather throw ValidatorException instead of above two lines here so that it ends up in <p:message>
} else {
ccmNameUnique = true;
}
}

Convert h:selectBooleanCheckbox value between boolean and String

I have a backing bean containing a field creditCard which can have two string values y or n populated from the DB. I would like to display this in checkbox so that y and n gets converted to boolean.
How can I implement it? I can't use a custom converter as getAsString() returns String while rendering the response whereas I need a boolean.
The <h:selectBooleanCheckbox> component does not support a custom converter. The property has to be a boolean. Period.
Best what you can do is to do the conversion in the persistence layer or to add extra boolean getter/setter which decorates the original y/n getter/setter or to just replace the old getter/setter altogether. E.g.
private String useCreditcard; // I'd rather use a char, but ala.
public boolean isUseCreditcard() {
return "y".equals(useCreditcard);
}
public void setUseCreditcard(boolean useCreditcard) {
this.useCreditcard = useCreditcard ? "y" : "n";
}
and then use it in the <h:selectBooleanCheckbox> instead.
<h:selectBooleanCheckbox value="#{bean.useCreditcard}" />
You can use the BooleanConverter for java primitives, this parses the text to boolean in your managedbean, at here just put in your code like this in you .xhtml file
<p:selectOneMenu id="id"
value="#{yourMB.booleanproperty}"
style="width:60px" converter="javax.faces.Boolean">
<p:ajax listener="#{yourMB.anylistener}"
update="anyIDcontrol" />
<f:selectItem itemLabel="------" itemValue="#{null}"
noSelectionOption="true" />
<f:selectItem itemLabel="y" itemValue="true" />
<f:selectItem itemLabel="n" itemValue="false" />
</p:selectOneMenu>
ManagedBean:
#ManagedBean(name="yourMB")
#ViewScoped
public class YourMB implements Serializable {
private boolean booleanproperty;
public boolean isBooleanproperty() {
return booleanproperty;
}
public void setBooleanproperty(boolean booleanproperty) {
this.booleanproperty = booleanproperty;
}
}
I had the similar problem, and I agree with previous post, you should handle this issues in persistence layer.
However, there are other solutions. My problem was next: I have TINYINT column in database which represented boolean true or false (0=false, 1=true). So, I wanted to display them and handle as a boolean in my JSF application. Unfortunately, that was not quite possible or just I didn't find a proper way. But instead using checkbox, my solution was to use selectOneMeny and to convert those values to "Yes" or "No". Here is the code, so someone with similar problem could use it.
Converter:
#FacesConverter("booleanConverter")
public class BooleanConverter implements Converter{
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
short number= 0;
try {
if (value.equals("Yes")) {
number= 1;
}
} catch (Exception ex) {
FacesMessage message = new FacesMessage();
message.setSeverity(FacesMessage.SEVERITY_FATAL);
message.setSummary(MessageSelector.getMessage("error"));
message.setDetail(MessageSelector.getMessage("conversion_failed") + ex.getMessage());
throw new ConverterException(message);
}
return number;
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
return value.toString();
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
JSF Page:
<h:selectOneMenu id="selectOnePlayerSucc" value="#{vezbaTrening.izvedenaUspesno}" converter="booleanConverter">
<f:selectItems id="itemsPlayerSucc" value="#{trainingOverview.bool}" var="opt" itemValue="#{opt}" itemLabel="#{opt}"></f:selectItems>
And in my ManagedBean I created a list with possible values ("Yes" and "No")
private List<String> bool;
public List<String> getBool() {
return bool;
}
public void setBool(List<String> bool) {
this.bool = bool;
#PostConstruct
public void init () {
...
bool = new LinkedList<>();
bool.add("Yes");
bool.add("No");
}

Resources