Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Primefaces datatable with column toggler conflicts with sort function on column

I have a data table that has a column toggler. When I uncheck a column and sort on a field the table is wrong. The header of the unchecked field pops back up and all data shift to the left, which leaves 1 column empty.

My table.xhtml file:

<h:form>    
    <p:dataTable id="registrations" var="registration" tableStyle="table-layout: auto;" widgetVar="registrationsTable" 
        value="#{overviewBean.listOfRegistrations}" 
        filteredValue="#{overviewBean.filteredListOfRegistrations}" emptyMessage="No registrations found with given criteria" >
        <f:facet name="header">
            <p:outputPanel style="text-align:left;">
                <h:outputText value="Search all fields: " />
                <p:inputText id="globalFilter" onkeyup="PF('registrationsTable').filter()" style="width:150px;" placeholder="Enter keyword"/>

                <p:commandButton id="toggler" type="button" value="Columns"  icon="ui-icon-calculator" style="float:right;"/>
                <p:columnToggler datasource="registrations" trigger="toggler" >
                </p:columnToggler>
            </p:outputPanel> 
        </f:facet>


        <p:column headerText="Active" visible="false">
            <h:outputText value="Y" />
        </p:column>

        <p:column headerText="Firstname" filterBy="#{registration.firstname}" filterStyle="display:none" sortBy="#{registration.firstname}">
            <h:outputText value="#{registration.firstname}" />
        </p:column>

        <p:column headerText="Lastname" filterBy="#{registration.lastname}" filterStyle="display:none" sortBy="#{registration.lastname}">
            <h:outputText value="#{registration.lastname}" />
        </p:column>

    </p:dataTable>
</h:form>
like image 741
david.carm Avatar asked Sep 27 '16 06:09

david.carm


2 Answers

I found my answer in this blog post: http://blog.primefaces.org/?p=3341

The solution was to keep the Visibility state of all columns in the backing bean.

The toggler must trigger the onToggle function in your backing bean:

<p:columnToggler datasource="registrations" trigger="toggler" >
    <p:ajax event="toggle" listener="#{overviewBean.onToggle}" />
</p:columnToggler>

Each column must be set by the boolean list in the backing bean:

<p:column headerText="Entry date" sortBy="#{registration.entryDate}" visible="#{overviewBean.list[0]}">
    <h:outputText value="#{registration.entryDate}">
        <f:convertDateTime pattern="dd/MM/yyyy" />
    </h:outputText>
</p:column>

In the backing bean you must have a list of booleans which represents the visibility of each field:

private List<Boolean> list;

public List<Boolean> getList() {
    return list;
}

public void setList(List<Boolean> list) {
    this.list = list;
}

public void onToggle(ToggleEvent e) {
    list.set((Integer) e.getData(), e.getVisibility() == Visibility.VISIBLE);
}

In the @PostConstruct method you must initialize this list of beans:

list = Arrays.asList(false, true, true);
like image 56
david.carm Avatar answered Sep 24 '22 14:09

david.carm


Alternative solution: create your own stateful toggler by subclassing the PrimeFaces p:columnToggler.

UPDATE: compensated for the fact that columns may have their rendered attribute set to false.

package my.domain;

import org.omnifaces.util.Components;
import org.primefaces.behavior.ajax.AjaxBehavior;
import org.primefaces.behavior.ajax.AjaxBehaviorListenerImpl;
import org.primefaces.component.column.Column;
import org.primefaces.component.columntoggler.ColumnToggler;
import org.primefaces.component.datatable.DataTable;
import org.primefaces.event.ToggleEvent;
import javax.el.MethodExpression;
import javax.faces.component.FacesComponent;
import javax.faces.context.FacesContext;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ComponentSystemEvent;
import javax.faces.event.ListenerFor;
import javax.faces.event.PostAddToViewEvent;
import java.io.IOException;

@FacesComponent(
    value = StatefulColumnToggler.COMPONENT_TYPE,
    createTag = true,
    tagName = StatefulColumnToggler.TAG_NAME,
    namespace = StatefulColumnToggler.NAMESPACE
)
@ListenerFor(systemEventClass=PostAddToViewEvent.class)
public class StatefulColumnToggler extends ColumnToggler {
    public static final String TAG_NAME = "statefulColumnToggler";
    public static final String COMPONENT_TYPE = "my.domain.statefulColumnToggler";
    public static final String NAMESPACE = "http://xmlns.domain.my/jsf/component";

    public void processEvent(ComponentSystemEvent event) throws AbortProcessingException {
        super.processEvent(event);
        if (event instanceof PostAddToViewEvent) {
            // This behaviour is static, so it does not have to be in the partial state: recreate it on every request.
            AjaxBehavior ajaxBehavior = (AjaxBehavior) getFacesContext().getApplication().createBehavior(AjaxBehavior.BEHAVIOR_ID);
            MethodExpression methodExpression = Components.createMethodExpression("#{component.onToggleHandler}", null, new Class<?>[]{ToggleEvent.class});
            ajaxBehavior.addAjaxBehaviorListener(new AjaxBehaviorListenerImpl(methodExpression, methodExpression));
            addClientBehavior("toggle", ajaxBehavior);
        }
    }

    public void onToggleHandler(ToggleEvent toggleEvent) {
        final DataTable dataTable = (DataTable) this.getDataSourceComponent();
        final int clientColumnIndex = (Integer) toggleEvent.getData();
        // Compensate for columns that are on the server, but not in the client.
        int columnsNotInClient = 0;
        for (int serverColumnIndex = 0; ; serverColumnIndex++) {
            if (serverColumnIndex >= dataTable.getColumns().size()) {
                throw new IllegalArgumentException("received index " + clientColumnIndex + " from client, but there is no rendered server side column with that index");
            }
            Column column = (Column) dataTable.getColumns().get(serverColumnIndex);
            if (!column.isRendered()) {
                columnsNotInClient++;
            }
            if (serverColumnIndex - columnsNotInClient == clientColumnIndex) {
                 column.setVisible(!column.isVisible());
                // Must delete any 'user' specified value expression, or it will take precedence over the toggled value.
                 column.setValueExpression(Column.PropertyKeys.visible.name(), null);
                break;
            }
        }
    }
}

Declare the namespace

xmlns:my=http://xmlns.domain.my/jsf/component

And add it to the page.

<my:statefulColumnToggler datasource="table_id" trigger="button_id" />
like image 27
Leo Mekenkamp Avatar answered Sep 20 '22 14:09

Leo Mekenkamp