Reputation: 31212
Suppose I have an h:form
with three fields and two submit buttons. The submit buttons are, say, Display Report and Generate Data. For the simplicity, I would prefer to have only one and not multiple forms. When Display Report, the values from the three fields are required as criteria for the report presentation. So I marked them as required="true"
but that disables the execution of Generate Data, which does not need those three fields.
Is there a way to make JSF form fields conditionally required without much custom coding, something like requiredIf=#{condition}
?
Upvotes: 1
Views: 8335
Reputation: 2810
If Generate Data action does not require any conversion or validation of form data then set the attribute immediate
to true
for this button:
<h:commandButton action="#{someBean.generateData}" value="Generate Data" immediate="true"/>
This way action generateData
is invoked before any conversion or validation takes place and form data is not validated at all.
If Generate data needs data from the form then you can use trick described by BalusC here: JSF 2.0 validation in actionListener or action method
In short, as @Jean-François suggested you can use EL expressions as value of required
attribute. The EL expression should evaluate to true
only when user pressed Display Report button. This could be done using the following expression: #{not empty param['<fullIdOfTheDisplayReportButton>']}
. This expression checks whether id of the button belongs to parameters, which means that given button was used to submit the form.
Full example:
<h:form id="formId">
<p>
Required only for Display Report: <h:inputText id="reqForDR" required="#{not empty param['formId:displayReportButton']}" />
</p>
<p>
Required for Display Report and Generate Data: <h:inputText id="reqForDRGD" required="true"/>
</p>
<h:commandButton id="displayReportButton" action="#{someBean.displayReport}" value="Display Report"/>
<h:commandButton id="generateDataButton" action="#{someBean.generateData}" value="Generate Data"/>
</h:form>
Upvotes: 5