JSF: How to get the selected item from selectOneMenu if its rendering is dynamic?

Posted by Dzmitry Zhaleznichenka on Stack Overflow See other posts from Stack Overflow or by Dzmitry Zhaleznichenka
Published on 2010-05-19T07:43:22Z Indexed on 2010/05/19 12:00 UTC
Read the original article Hit count: 617

Filed under:

At my view I have two menus that I want to make dependent, namely, if first menu holds values "render second menu" and "don't render second menu", I want second menu to be rendered only if user selects "render second menu" option in the first menu. After second menu renders at the same page as the first one, user has to select current item from it, fill another fields and submit the form to store values in database. Both the lists of options are static, they are obtained from the database once and stay the same. My problem is I always get null as a value of the selected item from second menu. How to get a proper value? The sample code of view that holds problematic elements is:

<h:selectOneMenu id="renderSecond" value="#{Bean.renderSecondValue}"
                                 valueChangeListener="#{Bean.updateDependentMenus}"
                                 immediate="true"
                                 onchange="this.form.submit();" >
                    <f:selectItems value="#{Bean.typesOfRendering}" />
                </h:selectOneMenu><br />

<h:selectOneMenu id="iWillReturnYouZeroAnyway" value="#{Bean.currentItem}"
                                 rendered="#{Bean.rendered}" >
                    <f:selectItems value="#{Bean.items}" />
                </h:selectOneMenu><br />
<h:commandButton action="#{Bean.store}" value="#Store" />

However, if I remove "rendered" attribute from the second menu, everything works properly, except for displaying the menu for all the time that I try to prevent, so I suggest the problem is in behavior of dynamic rendering. The initial value of isRendered is false because the default item in first menu is "don't render second menu". When I change value in first menu and update isRendered with valueChangeListener, the second menu displays but it doesn't initialize currentItem while submitting.

Some code from my backing bean is below:

public void updateDependentMenus(ValueChangeEvent value) {
    String newValue = (String) value.getNewValue();
        if ("render second menu" == newValue){
            isRendered = true;
        } else {
            isRendered = false;
        }
}

public String store(){
    System.out.println(currentItem);
    return "stored";
}

© Stack Overflow or respective owner

Related posts about jsf