Search code examples
jsfjsf-2uirepeat

accessing var outside ui:repeat JSF2


I want to access a variable through out my page. The var is declared inside a ui:repeat element. Heard that the scope of the variable in only inside the repeat tag. I want to load another div on the same page which need the details inside this var. How can I achieve this.

<ui:repeat var="errorDetails"
    value="#{adminDashboardController.errorDetails}" varStatus="status">

    <tr>
        <td>#{errorDetails.issueName}</td>
        <td>#{errorDetails.priority}</td>
        <td>#{errorDetails.comments}</td>
        <td><h:commandButton class="btn btn-primary btn-xs view-issue"
                value="View" /></td>
    </tr>
</ui:repeat>

<h4 class="modal-title" id="myModalLabel">#{errorDetails.issueName}</h4>

Solution

  • The errorDetails variable is only available in the scope of the ui:repeat.

    You have here two options:

    HTML/JS solution: Generate HTML code which contains one <h4...>#{errorDetails.issueName}</h4> for each line of your table and use JavaScript to display the right block when pressing on the command button.

    I think that this option should be only used for performance reason, because you will generate lot of HTML and because as a JSF developer you usually prefer to avoid coding custom things in JavaScript.

    JSF solution (my preferred one): use a backing bean to hold the currently viewed error detail. That would be something like this:

    <ui:repeat var="errorDetails" value="#{adminDashboardController.errorDetails}" varStatus="status">
        ...
        <h:commandButton ... action="#{adminDashboardController.showDetails(errorDetails)" update="myModalLabel" />
        ...
    </ui:repeat>
    
    ...
    
    <h:panelGroup rendered="#{adminDashboardController.currentDetail != null}">
        <h4 class="modal-title" id="myModalLabel">#{adminDashboardController.currentDetail.issueName}</h4>
    </h:panelGroup>
    

    The AdminDashboardController.showDetails methods would save the given error detail in a the field currentDetail.