Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple actionlisteners in JSF

I want to use multiple action listener to set state of two backing beans before further processing

1st way:

<p:commandButton process="@this" >
   <f:attribute name="key" value="#{node.getIdTestGroup()}" />
   <f:actionListener binding="#{testController.nodeListener}" />
<f:actionListener binding="#{testDeviceGroupController.prepareCreate}" />
</p:commandButton>

It give an exception:

WARNING: /testGroup/List.xhtml @26,88 binding="#{testController.nodeListener()}": Method nodeListener not found javax.el.ELException: /testGroup/List.xhtml @26,88 binding="#{testController.nodeListener()}": Method nodeListener not found

2nd way:

<p:commandButton process="@this" >
    <f:attribute name="key" value="#{node.getIdTestGroup()}" />
    <f:actionListener binding="#{testController.nodeListener(event)}" />
    <f:actionListener binding="#{testDeviceGroupController.prepareCreate(event)}" />
</p:commandButton>

Event is null on the nodeListener and prepareCreate methods

How to do it correct?

like image 604
smolarek999 Avatar asked May 04 '13 11:05

smolarek999


1 Answers

I see you facilitate the traditional approach of guess-how-it-works-using-bare-intuition-and-random-associations-then-act-surprised :-)

f:actionListener only lets you add a whole object as an observer, not an arbitrary method. You can either use type attribute to specify the class name (it will be instantiated by JSF) or binding attribute to give an instance of the object that you created by yourself (not a method!). The object must implement javax.faces.event.ActionListener.

Your second try (testDeviceGroupController.prepareCreate(event)) is wrong on many levels, but the crux is that the methods are called not to handle your action, but to create the Actionlistener instance.

You have a couple of options:

  • the sanest one: just make a method that calls each of the target methods. Since they are on different beans, you can inject one into the other.
  • if that doesn't work for you, you can create a method that creates a listener object.

Like this:

public ActionListener createActionListener() {
    return new ActionListener() {
        @Override
        public void processAction(ActionEvent event) throws AbortProcessingException {
            System.out.println("here I have both the event object, and access to the enclosing bean");
        }
    };
}

and use it like this:

<h:commandButton>
    <f:actionListener binding="#{whateverBean.createActionListener()}"/>            
</h:commandButton>
like image 161
fdreger Avatar answered Sep 25 '22 03:09

fdreger