Search code examples
jsfdisabled-controlviewparams

Enable\Disable commandbutton depending on URL parameter


JSF 2 allows to init URL parameter using <f:viewParam> tag.

For example:

<f:viewParam id="name" name="name"
            value="#{applicationBean.name}" required="true" />

and then use this parameter in the backing bean to load some objects using <f:event>.

For example:

<f:event type="preRenderView"
            listener="#{applicationBean.preRenderView}" />

The preRenderView() method in applicationBean sets some boolean variable buttonEnabled to either true\false

When using this variable in the main page to enable\disable button it doesn't work (e.g it always evaluates to false):

<h:commandButton disabled="#{!applicationBean.buttonEnabled}">

Any suggestions?


Solution

  • There's a timing problem. The action event is queued during apply request values phase. It will as part of safeguard against tampered requests also evaluate the disabled (and rendered) attribute at that point. However, as it's only actually set right before the render response phase, then it will indeed always evaluate to its default value, which is apparently false.

    You need to either perform the request parameter based initialization job in the @PostConstruct instead (the <f:viewParam> is then indeed insuitable), or to let the disabled attribute check the request parameter itself instead of a bean property (the bean property is then indeed insuitable).