Search code examples
jsffacelets

Best way to check for record existence in editor form


I'd like to implement a record detail page, which the user can call using a URL like:

  http://somewhere.foo/detail.jsf?recordId=1

Now if the record with the specified identfier can be found, the actual editor page should be displayed, if it cannot be found an error page should be displayed instead.

What's the best way to achieve this behaviour using JSF 2.0 and Facelets?

I thought of something like this (in pseudocode):

detail.xhtml

  <if #{!recordBean.recordFound}>
    <ui:include detailNotFound.xhtml>
  <else>
    ... show regular edit form here ...
  <endif>

Are the better or "more accepted" ways of doing this?


Solution

  • Use the rendered attribtue for this. Assuming that #{recordBean.list} returns a List, here's an example:

    <h:panelGroup rendered="#{empty recordBean.list}">
        <ui:include src="detailNotFound.xhtml" />
    </h:panelGroup>
    <h:panelGroup rendered="#{not empty recordBean.list}">
        ...
    </h:panelGroup>
    

    Or, if it are both include pages, then you could also use a conditional operator ?: straight in src of ui:include:

    <ui:include src="#{empty recordBean.list ? 'detailNotFound.xhtml' : 'showDetails.xhtml'}" />
    

    For the case you're interested, here are some more examples of possible boolean conditions in the rendered attribute:

    <h:someComponent rendered="#{bean.booleanValue}" />
    <h:someComponent rendered="#{bean.intValue > 10}" />
    <h:someComponent rendered="#{bean.objectValue == null}" />
    <h:someComponent rendered="#{bean.stringValue != 'someValue'}" />
    <h:someComponent rendered="#{!empty bean.collectionValue}" />
    <h:someComponent rendered="#{!bean.booleanValue and bean.intValue != 0}" />
    <h:someComponent rendered="#{bean.enumValue == 'ONE' or bean.enumValue == 'TWO'}" />