JSF @ViewScope, PrimeFaces <p:dialog and <ui:include

Olga picture Olga · Jun 6, 2013 · Viewed 7.4k times · Source

I have: button on main page and dialog.

A would like to have ViewScope life cycle for managed bean (NewDialog.java), what perform the dialog. In other words: recreate the NewDialog bean while pushing the button, and destroy while closing dialog.

But NewDialog bean has created while loading main page. How to force bean created only when you press a button?

<ui:composition
   <h:form id="mainForm">
      <p:commandButton value="New Dialog"
                  onclick="newDialogVar.show();"/>  
   </h:form>

        <ui:include src="#{viewScopedBean.page}.xhtml" />
    </ui:define>
</ui:composition>

Included page:

    <ui:composition ..
        <f:view >
       <h:form id="formId"
         <p:dialog appendToBody="false"
                  dynamic="true"
                  modal="true"
                  widgetVar="newDialogVar">

              <p:commandButton value="Ok"
                         actionListener="#{newDialog.ok}"/>
      </h:form>
    </p:dialog>
    </f:view>
</ui:composition>

Bean:

@ManagedBean
@ViewScoped
public class NewDialog implements Serializable{

  @PostConstruct
    protected void postConstruct() {
        LOG.info("----------------- PostConstruct -------------------");
    }
}

I use: PrimeFaces 3.5 with Mojarra 2.1.22

Thanks in advance!

P.S. : according research I add:

<context-param>
    <param-name>javax.faces.PARTIAL_STATE_SAVING</param-name>
    <param-value>false</param-value>
</context-param>

to web.xml.

Answer

BalusC picture BalusC · Jun 6, 2013

This is expected behavior. The <ui:include> runs during view build time, not during view render time. So even if you conditionally render one of its parents, it will still evaluate its src attribute during building/restoring of the view. In depth background explanation of "view build time" versus "view render time" can be found in this answer: JSTL in JSF2 Facelets... makes sense?

Your concrete functional requirement is unclear, so I can't elaborate the right approach in detail, but fact is, you need to look for an alternate approach if you want to postpone the creation of the bean to display of the dialog. Perhaps you need to split the bean in two ones, one holding the include path and another holding the dialog's data?