Calling Bootstrap 3 modal from JSF


Dialogs or modals can be used in JSF to create more dynamic, and interactive pages. This solution will show how to call a Bootstrap 3 modal from both a JSF commandLink, and a Primefaces commandLink. Each example uses a formId to update the modals content.

JSF h:commandLink

JSF implementation uses an onclick event, which shows the modal, then updates the form inside the modal. While the order of execution can be problamatic in that you could show stale data in your modal for a brief second; this solution will work for most cases.

<h:commandLink value="Show Modal" action="#{backingBean.doAction}"
    onclick="$('#myModal').modal('show');" immediate="true">
    <f:ajax execute="@this" render=":myForm"/>

It also should be noted that using the h:commandLink component requires a backing bean action.

Primefaces p:commandLink

The Primefaces component library has expanded the attributes available in the p:commandLink.  This functions the same as the h:commandLink, but uses less code to accomplish the same task.

<p:commandLink value="Show modal" styleClass="btn btn-primary" onclick="$('#myModal').modal('show');" update=":myForm" immediate="true" />

Bootstrap modal

The modal is straight forward. A p:commandLink is used to close the modal, and a form is wrapped around all important content that needs to be updated.

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModal" aria-hidden="true" data-keyboard="false" data-backdrop="static">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <h:form id="myForm">
                <div class="modal-header">
                    <h4 class="modal-title">Test Modal</h4>
                <div class="modal-body">
                    Content area
                <h:panelGroup layout="block" styleClass="modal-footer">
                    <p:commandLink value="Close" immediate="true" styleClass="btn btn-default" oncomplete="$('#myModal').modal('hide');" />

Self managing your own modals may be more work than using a prebuilt component like primefaces dialog. But the benefit is that the modal is responsive, and you still have full control over the design.