Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SelectOneMenu updates other SelectOneMenu [duplicate]

I want to update the second SelectOneMenu when I select any item of the first SelectOnMenu. As it is now, I get the values for the SelectOneMenus from a ManagedBean. I guess I've to use AJAX (jquery) to send parameters to the ManagedBean.

<h:form>
    <div class="center">
        <h:panelGrid id="editTable" columns="2" styleClass="center">
            ...
            <h:outputText value="#{msg.timetable_list_category}" />
            <h:selectOneMenu class="category">
                <f:selectItems value="#{categoryBackingBean.categorys}" var="c"
                    itemLabel="#{c.category_Name}" itemValue="#{c.id}" />
            </h:selectOneMenu>

                <h:outputText value="#{msg.timetable_list_seminarblock}" />
            <h:selectOneMenu class="seminarblock">
                <f:selectItems value="#{seminarblockBackingBean.seminarblocks}" var="s"
                    itemLabel="#{s.seminarblock_Name}" itemValue="#{s.seminarblock_Id}" />
            </h:selectOneMenu>
            ...
        </h:panelGrid>
        ...
    </div>
</h:form>
like image 1000
thomas.st Avatar asked Sep 21 '12 15:09

thomas.st


1 Answers

Actually you can use a ValueChangeListener that is invoked when the value of your selectOneMenu changes:

<h:selectOneMenu class="category" valueChangeListener="#{yourBean.selectOneMenuListener}">
    <f:selectItems value="#{categoryBackingBean.categorys}" var="c"
        itemLabel="#{c.category_Name}" itemValue="#{c.id}" />
</h:selectOneMenu>

Then, in your bean you have this method:

public void selectOneMenuListener(ValueChangeEvent event) {
    //This will return you the newly selected
    //value as an object. You'll have to cast it.
    Object newValue = event.getNewValue(); 
    //The rest of your processing logic goes here...
}

To update the page you can either add onchange="submit()" to your <h:selectOneMenu/>. For some partial rendering you can try adding this <f:ajax/> instead of onchange="submit()":

<h:selectOneMenu class="category" valueChangeListener="#{yourBean.selectOneMenuListener}">
    <f:selectItems value="#{categoryBackingBean.categorys}" var="c"
        itemLabel="#{c.category_Name}" itemValue="#{c.id}" />
    <f:ajax event="change" execute="@form" render="theIdOfTheComponentYouWantToReRender"/>
</h:selectOneMenu>

If I'm not mistaken you'll want to get the id of the element selected in the first menu and populate the second one according to it. Then you can render the other selectOneMenu or, if needed, a panel wrapping a part of your form.

like image 123
Fritz Avatar answered Oct 27 '22 13:10

Fritz