JSF 2: Cannot choose default entry in dropdown element when dropdown is required and default entry is null

守給你的承諾、 提交于 2019-12-22 17:48:38

问题


I have the following JSF 2 code:

    <p:selectOneMenu id="dropdown" value="#{data.selection}" required="true" converter="selectOneMenuConverter">
            <f:selectItem itemLabel="Select one..." itemValue="" noSelectionOption="true" />
            <f:selectItems value="#{data.entries}" var="entry" itemLabel="#{entry.name}" itemValue="#{entry}" />
            <p:ajax update="display" event="change" />
    </p:selectOneMenu>

    <h:panelGroup id="display">
            <h:outputText value="#{data.selection}" />
    </h:panelGroup>

Everything works as expected when I choose a value from the dropdown. When the user "deselects" an entry by choosing "Select One", JSF complains that this is not possible because the selectonemenu is required.

The problem comes from there that the p:ajax makes a partial submit that triggers validation. Immediate=true does also not work because in case the immediate happens on an input field (like selectonemenu is) a validation is performed. The validation shall only happen when the user presses the "go on" button on the bottom of the page (not shown in code)

Further the given converter converts the Strings to Objects and for the default value it returns null (that's also the expected value within the domain for "no selection").

So my question is what I must do to fulfill my case. For my this is a standard case and I cannot imagine that there is no solution for this.

Any ideas?

Best regards, Florian


回答1:


The validation shall only happen when the user presses the "go on" button on the bottom of the page (not shown in code)

Then just tell the dropdown's required attribute to do exactly that instead of hardcoding a true.

<h:form id="form">
    <p:selectOneMenu ... required="#{not empty param['form:go']}">
        ...
    </p:selectOneMenu>

    ...

    <p:commandButton id="go" ... />
</h:form>

The #{not empty param['form:go']} will only evaluate true when the form submit has actually been taken place by the submit button which has the client ID form:go in the particular example. If you don't like hardcoding client IDs either, then reference it as follows:

<h:form>
    <p:selectOneMenu ... required="#{not empty param[go.clientId]}">
        ...
    </p:selectOneMenu>

    ...

    <p:commandButton binding="#{go}" ... />
</h:form>


来源:https://stackoverflow.com/questions/13419003/jsf-2-cannot-choose-default-entry-in-dropdown-element-when-dropdown-is-required

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!