0
votes

Following example:

<h:selectOneMenu value="#{bean.value}">
    <f:selectItem itemValue="#{null}" itemDisabled="#{true}" noSelectOption="#{true}" itemLabel="choose one" />
    <f:selectItem itemValue="FEMALE" itemLabel="female" />
    <f:selectItem itemValue="MALE" itemLabel="male" />
    <f:converter converterId="myConverter" />
</h:selectOneMenu>

On initial load the value of the bean is null so the please-choose-option is selected. If the user chooses nothing the browser won’t submit a value (the selected option is disabled) and JSF will set the value to an empty String. If the page is rendered again there is no according value, JSF won't render a selected-attribute and most browsers will preselect the first non-disabled-value. Bad.

I thought I could easily change this with a Converter which converts the empty String to null in getAsObject. But in this case the converter is not called.

Anybody knows why?

I know that I could change this behaviour with javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL but this leads to other problems with other fields.

1
I tend to use the value '-' as the 'no-selection' value. That is easily identifiable server-side, not likely to cause a conflict and it is not an empty string or null :)Gimby
Thanks, but won’t help me :( The value '-' will also be replaced by an empty String. Problem is that the select-element is disabled so the browser won’t submit something but JSF will change the value. I’ll update my question.lefloh
Making the field required is not an option? The setup to me seems that it is a mandatory selection. I must admit I have no experience with making items disabled, I just let the value submit and deal with the poor selection choice server side.Gimby
Actually this field is required. But only if the user wants to proceed. My problem happens if the user goes back one page and then continues.lefloh
why do you have to disable that null option?Mr.J4mes

1 Answers

0
votes

I solved my problem by setting the selected-attribute manually:

<f:selectItem itemValue="#{null}" itemDisabled="#{true}" noSelectOption="#{true}" itemLabel="choose one" />
  <f:passThroughAttributes value="#{bean.attributes}" />
</f:selectItem>

public Map<String, String> getAttributes() {
    Map<String, String> attributes = new HashMap<>();
        if (value == null || "".equals(value)) {
           attributes.put("selected", "selected");
        }
    }   
    return attributes;
}