Search code examples
jsf-2viewparams

Required flag on f:viewParam doesn't prevent preRenderView to be called


some of my viewParams are mandatory and a FacesMessage is shown when they are missing. However the system event preRenderView is excecuted with empty search parameters and thus there is a default data result returned. Is there anyway to prevent preRenderView registered methods to be executed when the required attribute is violated?


Solution

  • The <f:event type="preRenderView"> is in this construct in essence a hack/workaround. It's as its name says indeed always invoked before render response phase regardless of the type request (postback or not) and the validation result (fail or not). This is also in detail elaborated in this related question: What can <f:metadata>, <f:viewParam> and <f:viewAction> be used for? This contains the following snippet which should help you further:

    public void init() {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        if (!facesContext.isPostback() && !facesContext.isValidationFailed()) {
            // ...
        }
    }
    

    Put the desired logic there in place of // ....

    In JSF 2.2, a standard solution is available in flavor of <f:viewAction>, also demonstrated in the aforementioned related question.