How to disable the required tag on a selectOneMenu when p:ajax event=change?

青春壹個敷衍的年華 提交于 2019-12-12 09:43:43

问题


Here is my configuration:

  • PrimeFaces: 4.0.4 (elite)
  • OmniFaces: 1.6.3
  • JSF: MyFaces 2.0.2
  • Server: WebSphere 8.5.0.2

Some code (I only post the relevant part for better clarity):

<p:selectOneMenu value="#{viewModel.selectedContact}" required="true" converter="omnifaces.SelectItemsConverter">
    <p:ajax event="change" listener="#{viewModel.updateContact}" update="area"/> 
    <f:selectItem itemValue="#{null}" itemLabel="#{msg.no_contact}" noSelectionOption="true" />
    <f:selectItems value="#{viewModel.contacts}"/> 
</p:selectOneMenu>

So here, we have a simple p:selectOneMenu that contains a list of Contact objects as well as a "No Contact" option. This field is required if I want to submit the form.

When a contact is selected in the list, the updateContact method is called. This method will generate data that will be displayed in the area section of the page updated by the AJAX call.

If I select the "No Contact" option, a validation error is triggered as this field is required, so the updateContact method is not called. I would like the method to be called as I would need to reset some data then hide the area section of the page.

I have tried using process="@this", immediate="true", but it doesn't work. With immediate="true", the selected Contact is not passed to the updateContact method.

So, what is the best way to bypass the validation of this field when selecting a null value?


回答1:


Let the required attribute check if the command button is invoked. You can check that by the presence of the button's client ID in the request parameter map.

<p:selectOneMenu ... required="#{not empty param[save.clientId]}" />
...
<p:commandButton binding="#{save}" ... />

(note: code is as-is, you don't need a bean property for this)

If the command button is not invoked (but instead the ajax change listener is invoked), then the required attribute will evaluate false and everything will go as you intented.


Update: as per the comments, you intend to make them appear like required during render response all time. So, just add that check:

<p:selectOneMenu ... required="#{not empty param[save.clientId] or facesContext.currentPhaseId.ordinal eq 6}" />
...
<p:commandButton binding="#{save}" ... />


来源:https://stackoverflow.com/questions/20263179/how-to-disable-the-required-tag-on-a-selectonemenu-when-pajax-event-change

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