Link19
Link19

Reputation: 606

Can I add object represented by selectOneMenu to a collection in a bean in JSF?

So I have bean named element that has a list of categories in and I want to add to that list from a drop down box.

There is a submit at the bottom of the page that persists my element and all works fine, I have a converter in place for the drop down which is also working, but I can't work out how to get an object of type Category from my drop down and add it to the category list in my bean.

Here is the section of my JSF I'm trying to achieve this from:

<table>
<tr>
    <th class="textRight">Choose Category</th>
    <td>
        <h:selectOneMenu id="currentCategory">
            <f:selectItems value="#{serviceWeb.listCategories()}" />
        </h:selectOneMenu>
    </td>
    <td>
        <h:commandButton id="addCategory" value="Add" 
                         action="element.categories.add(#{currentCategory.value})"  />
    </td>
</tr>
</table>

I know this doesn't work, I get the error:

action="element.categories.add(#{currentCategory.value})" Not a Valid Method Expression

to explain, there is no backing bean for this menu item, I'm trying to get the value from the component itself.

So I guess you can't do it this way, but how do you do it?

Is it possible?

Upvotes: 3

Views: 664

Answers (1)

BalusC
BalusC

Reputation: 1108642

Bind the component to the view (which will in case of <h:selectOneMenu> resolve to an instance of HtmlSelectOneMenu) and use UIInput#getValue() as action method argument and fix your invalid EL syntax.

<h:selectOneMenu binding="#{currentCategory}">
    <f:selectItems value="#{serviceWeb.listCategories()}" />
</h:selectOneMenu>
<h:commandButton value="Add" action="#{element.categories.add(currentCategory.value)}" />

Upvotes: 2

Related Questions