Invoke action method on click of h:selectOneMenu

和自甴很熟 提交于 2020-01-13 07:44:05

问题


I have the following drop down list:

<h:selectOneMenu value="#{user.favCoffee3}"  onclick="">
   <f:selectItems value="#{user.favCoffee3Value}" var="c"
   itemLabel="#{c.coffeeLabel}" itemValue="#{c.coffeeValue}" />
</h:selectOneMenu>

I would like to launch some method from the bean by drop down list item click. How can I achieve it?


回答1:


You can use the valueChangeListener attribute, pointing to a method in the managed-bean and add a submit() in the onchange attribute.

The form should look like :

<h:form>
    <h:selectOneMenu valueChangeListener="#{bean.valueChanged}" 
                     onchange="submit()">
        <f:selectItem itemValue="1" itemLabel="First" />
        <f:selectItem itemValue="2" itemLabel="Second" />
    </h:selectOneMenu>
</h:form>

And the valueChangeListener method in the managed bean would be:

public void valueChanged(ValueChangeEvent event) {
    //do your stuff
}



回答2:


As part of the basic JSF toolkit, you can use the <f:ajax/> tag to submit (using ajax) your input without need for a full page submit/refresh. Using your code sample

  1. Define the <f:ajax/> tag as a child of the dropdown menu

    <h:selectOneMenu value="#{user.favCoffee3}"  onclick="">
       <f:selectItems value="#{user.favCoffee3Value}" var="c" itemLabel="#{c.coffeeLabel}" itemValue="#{c.coffeeValue}" />
       <f:ajax listener="#{user.doSomething}"/>
    </h:selectOneMenu>
    
  2. Define a method (doSomething() in this example) in your backing bean that accepts an instance of AjaxBehaviorEvent

    public void doSomething(AjaxBehaviorEvent abe){
      //do what you want with your favCoffee3 variable here
    }
    

Further reading:

  • The <f:ajax/> tag documentation by oracle



回答3:


Seems to work for a4j:support. Your h:selectOneMenu would look like this:

<h:selectOneMenu value="#{user.favCoffee3}">
    <f:selectItems value="#{user.favCoffee3Value}" var="c" itemLabel="#{c.coffeeLabel}" itemValue="#{c.coffeeValue}" />
    <a4j:support event="onchange" action="#{user.onSelectOneMenuChange}">
</h:selectOneMenu>

You also need to add the following taglib:

<%@ taglib uri="http://richfaces.org/a4j" prefix="a4j"%>


来源:https://stackoverflow.com/questions/18787653/invoke-action-method-on-click-of-hselectonemenu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!