GWT Header checkbox to check / uncheck all checkboxes in my table

Erasio picture Erasio · Jul 17, 2012 · Viewed 7k times · Source

I´ve created an CellTable with the Google Web Toolkit. I just started using it and my knowledge about it is very small... However I was searching for a tutorial or just a code example of how to create a checkbox in the CellTable header but everythin I´ve found I didn´t understand or it didn´t worked.

So far I´ve got this code to create a Column for checkboxes and a normal table mostly the same as the Google tutorial for a CellTable:

Column<Contact, Boolean> checkColumn = new Column<Contact, Boolean>(
new CheckboxCell(true, false)) {

@Override
public Boolean getValue(Contact contact) {
    return null;
}

};

table.addColumn(checkColumn, SafeHtmlUtils.fromSafeConstant("<br/>"));
table.setColumnWidth(checkColumn, 40, Unit.PX);

Now I´m searching for the code to add a checkbox to the header and how to make it check or uncheck all checkboxes.

Thanks for your time.

Answer

Papick G. Taboada picture Papick G. Taboada · Jul 17, 2012

From my blog post:

Here is a simple column header that selects/ de-selects all rows in a table. When all rows are checked, the header becomes checked automatically. Clicking the checkbox in the header causes either to select or de-select all rows.

selection

I am using the selection model and the data list provider to do the selection magic. It may not work for everyone.

And here is my custom header:

public final class CheckboxHeader extends Header {

    private final MultiSelectionModel selectionModel;
    private final ListDataProvider provider;

    public CheckboxHeader(MultiSelectionModel selectionModel,
            ListDataProvider provider) {
        super(new CheckboxCell());
        this.selectionModel = selectionModel;
        this.provider = provider;
    }

    @Override
    public Boolean getValue() {
        boolean allItemsSelected = selectionModel.getSelectedSet().size() == provider
                .getList().size();
        return allItemsSelected;
    }

    @Override
    public void onBrowserEvent(Context context, Element elem, NativeEvent event) {
        InputElement input = elem.getFirstChild().cast();
        Boolean isChecked = input.isChecked();
        for (TYPE element : provider.getList()) {
            selectionModel.setSelected(element, isChecked);
        }
    }

}