2

I am using JSF 2.2 and I was wondering if there is a way to render components with ajax conditionally only if the validation passes. By using the render attribute of ajax the components will be rendered regardless of the validation passing or not. What I'm after is something like:

<f:ajax ... render="#{validationHasPassed ? 'foo' : ''}" />
...
<h:panelGroup id="foo">
          <!-- other components here -->
  </h:panelGroup>

Is it possible to conditionally render a component in a similar way like this? In my case I don't want to have the rendered attribute in a fragment and set it to true or false, as this makes the fragment not exist at all in the DOM if validation fails. I might have specific css styling for example in the components inside the panelGroup that has been acquired through jQuery after some interaction with the page and I don't want to render the section if validation fails, so that it can remain in its current visual state.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Gabriel
  • 67
  • 2
  • 6

1 Answers1

2

You can make use of FacesContext#isValidationFailed(). It will return true if validation has failed in the current JSF lifecycle. The current instance of FacesContext is available also in EL as #{facesContext}.

Just check it in the rendered attribute and update its parent placeholder component. Do note that you can't conditionally render a component which has by itself rendered attribute set as JavaScript would otherwise not be able to find and update it. Your theoretical <f:ajax> attempt would have failed the same way.

E.g.

<f:ajax ... render="foo-holder" />
...
<h:panelGroup id="foo-holder">
    <h:panelGroup id="foo" rendered="#{not facesContext.validationFailed}">
        Validation has not failed.
    </h:panelGroup>
</h:panelGroup>

Add if necessary layout="block" to make them <div> components instead of <span> ones, depending on the final markup.

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Thank you for your answer BalusC. I should have explained more clearly what exactly I want to do. I have edited my question to clarify it. – Gabriel May 31 '15 at 22:49
  • And I added some more logical explanation and pieces of answer behind "See also" link into the answer. As to the edited question, I have further improved the edit. In the future, please don't change the question in such way that the answer becomes completely invalidated (in your particular case, I seemed to only answer which you already knew for long, which look really confusing and stupid to future readers). If you really needed to, you'd better ask a new question, else the answerer will likely just delete the answer altogether and downvote the question. – BalusC Jun 01 '15 at 07:32