Question

Consider the following code:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:o="http://omnifaces.org/ui">

    <f:metadata>
        <o:viewParam name="selected" value="#{testBacking.selected}" >
        </o:viewParam>
    </f:metadata>

    <h:head>
        <title>
            title
        </title>

    </h:head>

    <h:body>
        <o:form includeViewParams="true">
            <h:commandButton action="#{testBacking.go()}" value="go">
                <f:ajax execute="@all" render="@all"/>
            </h:commandButton>
        </o:form>
    </h:body>

</html>

The action method:

public void go() {
    System.out.println("go() is called");

    Collection<UIViewParameter> viewParams = ViewMetadata.getViewParameters(FacesContext.getCurrentInstance().getViewRoot());

    for (UIViewParameter viewParam : viewParams) {
        System.out.println(viewParam.getName() +" = "+ viewParam.getValue());
    }
}

The action method returns correct viewParam name, but the value always null. If this is the intended behaviour, how <o:form includeViewParams="true"> helps in practical usage?

I am using Mojarra 2.1.12 and Omnifaces 1.1.

Was it helpful?

Solution

Your bean is apparently request scoped. The <o:viewParam> is intented to be used in combination with view scoped beans only because it prevents the model being converted/validated/updated again and again on every postback to the same view even though it was already done during the initial request and is still there as property of the view scoped bean. This improves overall performance when the model is being bound to an expensive converter which performs the job based on DB calls. The showcase example also shows this clearly.

To achieve this, the <o:viewParam> basically skips this model conversion/validation/update job during any postback. A request scoped bean is however newly created on every request and the initial model value is thus lost on every postback and due to the design of <o:viewParam> not being set at all.

You can solve this by placing the bean in the view scope, or by just using the standard <f:viewParam> instead.

As to the <o:form includeViewParams="true">, this is only useful on synchronous postbacks. If you remove the <f:ajax> then you'll see how it's useful. Without includeViewParams="true" the URL becomes the one without the view parameter, i.e. without ?selected=somevalue and it becomes thus unbookmarkable. This has no strict relationship with <o:viewParam>, it works as good in combination with <f:viewParam>.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top