jsfviewparams

f:viewParam lost after ajax call


I have this f:viewParam to set value and do search in back bean in view:

<f:metadata>
<f:viewParam name="id"
    value="#{editorBean.id}"
    required="true" />
<f:event type="preRenderComponent"
    listener="#{editorBean.search}" />
...

Back bean:

private String id; // getters setters

public void search(ComponentSystemEvent event) {


    if (id != null) {
            //search data in DB to construct TreeNode finBy(id)...
...

In browser I can't expand the second level of tree, because in backing Bean the id is null..

enter image description here

Debug:

enter image description here

How to f:viewParam be set in all calls?


Solution

  • It's caused because the <h:form> submits by default to an URL without the query string.

    Either put the bean in the view scope,

    @ManagedBean
    @ViewScoped
    public class EditorBean {
    

    and skip the prerenderview during postback

    public void search(ComponentSystemEvent event) {   
        if (FacesContext.getCurrentInstance().isPostback()) {
            return;
        }
    
        // ...
    } 
    

    A view scoped bean lives as long as you interact with the same view and thus the properties doesn't need to be initialized again and again.

    Or make use of OmniFaces <o:form> which offers an includeViewParams attribute to include view parameters in form action URL:

    <o:form includeViewParams="true">
    

    See also: