Search code examples
jsfactionlistener

JSF multiple actionListeners called in order with update


Using JSF 2 I understand I can call multiple actionListeners as such:

<h:commandButton value="Action">
    <f:actionListener binding="#{myBean.actionOne()}" />
    <f:actionListener binding="#{myBean.actionTwo()}" />
</h:commandButton>

However, I would like to call one actionListener and perform an update to the @form. Once this first call and update are complete call a 2nd actionListener and perform another update. Is this possible?


Solution

  • Yes. With <h:commandScript>.

    <h:form>
        ...
        <h:commandButton value="Action" action="#{myBean.actionOne}">
            <f:ajax render="@form" onevent="function(data) {
                if (data.status === 'success') actionTwo();
            }"/>
        </h:commandButton>
        <h:commandScript name="actionTwo" action="#{myBean.actionTwo}"
             render="...">
        </h:commandScript>
    </h:form>
    

    In case you're not on JSF 2.3 yet, see How to invoke a JSF managed bean on a HTML DOM event using native JavaScript? for alternatives.

    In case you're using PrimeFaces (given away by your question history confirms this and using the term 'update' instead of 'render'), the <p:remoteCommand> is the equivalent.

    <h:form>
        ...
        <p:commandButton value="Action" action="#{myBean.actionOne}"
             update="@form" oncomplete="actionTwo()">
        </p:commandButton>
        <p:remoteCommand name="actionTwo" action="#{myBean.actionTwo}"
             update="...">
        </p:remoteCommand>
    </h:form>