30

Is it possible to execute two methods in action of <h:commandButton>?

For example,

<h:commandButton action="#{bean.methodOne();bean.methodTwo();}" />
Tiny
  • 27,221
  • 105
  • 339
  • 599
IAdapter
  • 62,595
  • 73
  • 179
  • 242

3 Answers3

57

You can use f:actionListener like this.

  <h:commandButton action="#{bean.methodOne()}">
    <f:actionListener binding="#{bean.methodTwo()}" />
  </h:commandButton>

You can add as many f:actionListener elements as you need.

bruno
  • 2,213
  • 1
  • 19
  • 31
Narendra Yadala
  • 9,554
  • 1
  • 28
  • 43
  • 2
    Are those actions executed in order? – renraku Jan 23 '18 at 10:42
  • Here https://stackoverflow.com/questions/24806943/multiple-action-listeners-with-a-single-command-component-in-jsf it says in the accepted answer "Anyway, keep in mind the listeners are always executed before the action..." – A.Alessio Jul 14 '21 at 12:49
6

Add a methodThree in your bean :

public Object methodThree() {
    methodOne();
    methodTwo();
    return someThing;
}

And call this method from the JSF page.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • 2
    I know I can do that, but I can't call two methods in action? – IAdapter Oct 27 '11 at 07:28
  • 1
    From the Mojarra javadoc for the `h:commandButton` `action` attribute: _MethodExpression representing the application action to invoke when this component is activated by the user. The expression must evaluate to a public method that takes no parameters, and returns an Object (the toString() of which is called to derive the logical outcome) which is passed to the NavigationHandler for this application._ – Matt Handy Oct 27 '11 at 07:30
  • Thanks Matt. I edited my answer to reflect the fact that an object must be returned. – JB Nizet Oct 27 '11 at 07:36
  • void is currently also allowed – Kukeltje Jul 05 '17 at 11:33
1

The accepted answer was close to working for me but the semi-colon was throwing a parse exception. The below code worked:

<h:commandButton>
    <f:actionListener binding="#{bean.methodTwo()}" />
</h:commandButton>
Tony Scialo
  • 5,457
  • 11
  • 35
  • 52