Search code examples
javajsflistenericefacesmenuitem

JSF Adding Action Listeners


I'm creating a MenuItem dynamically and I want to add a custom listener when the MenuItem is clicked.

I've tried adding addActionListener and setActionListener but neither of these get called when the link is clicked.

It appears that there is a List called "listeners" attached to MenuItem (I can see this when debugging a MenuItem setup with the listener statically). Any idea how to add the listener correctly?


Solution

  • They needs to be created and added as follows (copied from one of my previous answers):

    FacesContext context = FacesContext.getCurrentInstance();
    MethodExpression actionListener = context.getApplication().getExpressionFactory()
        .createMethodExpression(context.getELContext(), "#{bean.actionListener}", null, new Class[] {ActionEvent.class});
    uiCommandComponent.addActionListener(new MethodExpressionActionListener(actionListener));
    

    ...where #{bean.actionListener} actually exists and is declared like follows in the backing bean class associated with the managed bean name bean:

    public void actionListener(ActionEvent event) {
        // ...
    }
    

    More importantingly, you need to give any dynamically created UICommand (and UIInput) component in question a fixed ID as well, else it will get an autogenerated ID which may cause that JSF cannot locate/correlate it during the apply request values phase.

    Thus, do so as well:

    uiCommandComponent.setId("someFixedId");