Thursday, February 5, 2015

Re: How to implement select all checkbox header for cell table

Clase con el Grid:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.webgocommerce.client.view.grid;

import com.google.gwt.cell.client.Cell;
import com.google.gwt.cell.client.CheckboxCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.cell.client.NumberCell;
import com.google.gwt.cell.client.TextCell;
import com.google.gwt.cell.client.TextInputCell;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.DataGrid;
import com.google.gwt.user.cellview.client.Header;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.client.Window;
import com.google.gwt.view.client.DefaultSelectionEventManager;
import com.google.gwt.view.client.MultiSelectionModel;
import com.google.gwt.view.client.SelectionModel;
import com.google.web.bindery.event.shared.EventBus;
import com.google.web.bindery.event.shared.SimpleEventBus;
import com.webgocommerce.client.beanproxy.PrecioItemProxy;
import com.webgocommerce.client.requestfactory.ContextMantenimientoPrecioItem;
import com.webgocommerce.client.requestfactory.FactoryGestion;
import com.webgocommerce.client.resource.MyResource;
import com.webgocommerce.client.uiutil.CheckCellHead;
import com.webgocommerce.client.uiutil.FilteredListDataProvider;
import com.webgocommerce.client.uiutil.IFilter;
import com.webgocommerce.client.view.uisesion.UISesionImpl;
import com.webgocommerce.shared.FieldVerifier;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 *
 * @author SISTEMAS
 */
public class GridPrecioItem extends DataGrid<PrecioItemProxy> {
    public final static String E="E";
    public final static String L="L";
    private String modo;
    private final FactoryGestion FACTORY = com.google.gwt.core.client.GWT.create(FactoryGestion.class);
    private final EventBus EVENTBUS = new SimpleEventBus();
    private List<PrecioItemProxy> data = new ArrayList<PrecioItemProxy>();
    private HashSet<Integer> indexUpdates = new HashSet();
    private final MultiSelectionModel<PrecioItemProxy> selectionModel = new MultiSelectionModel<PrecioItemProxy>();
    private FilteredListDataProvider<PrecioItemProxy> dataProvider = new FilteredListDataProvider<PrecioItemProxy>(new IFilter<PrecioItemProxy>() {

        @Override
        public boolean isValid(PrecioItemProxy value, String filter) {
            if (filter == null || value == null) {
                return true;
            } else {
                String values = value.getId().toString().toLowerCase() + " " + value.getCodigo().toLowerCase() + " " + value.getMarca().toLowerCase() + " " + value.getDescripcion().toLowerCase();
                return values.contains(filter.toLowerCase());
            }
        }
    });

    private SimplePager pager;

    public GridPrecioItem() {
        initComponents();
        //initStyle();
    }

    private void initComponents() {
        this.setWidth("100%");
        this.setHeight("90%");
        initColumns();
        initEditColumns();
        this.setRowCount(data.size(), true);
        this.setRowData(0, data);
        dataProvider.setList(data);
        dataProvider.addDataDisplay(this);
        this.setVisible(true);
        SimplePager.Resources pagerResources = GWT.create(SimplePager.Resources.class);
        pager = new SimplePager(SimplePager.TextLocation.CENTER, pagerResources, false, 0, true);
        pager.setDisplay(this);
        pager.setVisible(true);
        this.setSelectionModel(selectionModel, DefaultSelectionEventManager.<PrecioItemProxy>createCheckboxManager());
    }

    private void initColumns() {
        this.addColumn(checkColumn, headCheckAll);
        this.addColumn(estado, "EST");
        this.addColumn(codigo, "CODIGO");
        this.addColumn(descripcion, "DESCRIPCION");
        this.addColumn(marca, "MARCA");
        this.addColumn(precioSd, "PRECIOSD");
        this.addColumn(descuento, "DESCUENTO");
        this.addColumn(precioVenta, "P. VENTA");
        this.addColumn(valorVenta, "VALOR VENTA");
        this.addColumn(igv, "IGV");
        this.setColumnWidth(checkColumn, 6, Unit.PCT);
        this.setColumnWidth(estado, 6, Unit.PCT);
        this.setColumnWidth(codigo, 10, Unit.PCT);
        this.setColumnWidth(marca, 15, Unit.PCT);
        this.setColumnWidth(descripcion, 25, Unit.PCT);
    }

    private void calcularPrecioSd(int index, PrecioItemProxy object, String value) {
        if (FieldVerifier.isNumber(value)) {
            ContextMantenimientoPrecioItem context = FACTORY.contextMantenimientoPrecioItem();
            FACTORY.initialize(EVENTBUS);
            PrecioItemProxy beanEdit = context.edit(object);
            BigDecimal valprecioSd = BigDecimal.valueOf(Double.parseDouble(value));
            BigDecimal valDescuento = object.getDescuento();
            BigDecimal valPrecioVenta = valprecioSd.subtract(valDescuento);
            BigDecimal valValorVenta = valPrecioVenta.divide(UISesionImpl.beanInitParam.getIgv().divide(BigDecimal.valueOf(100), 5, RoundingMode.HALF_UP).add(BigDecimal.ONE), 5, RoundingMode.HALF_UP);
            BigDecimal igv = valPrecioVenta.subtract(valValorVenta);
            beanEdit.setPrecioSD(valprecioSd);
            beanEdit.setDescuento(valDescuento);
            beanEdit.setPrecioVenta(valPrecioVenta);
            beanEdit.setValorVenta(valValorVenta);
            beanEdit.setIgv(igv);
            //GWT.log("Index Vista: " + index);
            //Window.alert("inicio"+index);
            //index = dataProvider.getList().indexOf(object);
            //Window.alert("fin"+index);
            int indexModel = data.indexOf(object);
            //GWT.log("Index Modelo: " + indexModel);
            data.set(indexModel, beanEdit);
            indexUpdates.add(indexModel);
            context.fire();
            dataProvider.refresh();
            // Update the row and subrow.
            setKeyboardSelectedRow(index, 0, true);
            // Update the column index.
            setKeyboardSelectedColumn(5, true);
        } else {
            Window.alert("escriba un numero");
        }
    }

    private void calcularDescuento(int index, PrecioItemProxy object, String value) {
        if (FieldVerifier.isNumber(value)) {
            ContextMantenimientoPrecioItem context = FACTORY.contextMantenimientoPrecioItem();
            FACTORY.initialize(EVENTBUS);
            PrecioItemProxy beanEdit = context.edit(object);
            BigDecimal valPrecioSd = object.getPrecioSD();
            BigDecimal valDescuento = BigDecimal.valueOf(Double.parseDouble(value));
            BigDecimal valPrecioVenta = object.getPrecioSD().subtract(valDescuento);
            BigDecimal valValorVenta = valPrecioVenta.divide(UISesionImpl.beanInitParam.getIgv().divide(BigDecimal.valueOf(100), 5, RoundingMode.HALF_UP).add(BigDecimal.ONE), 5, RoundingMode.HALF_UP);
            BigDecimal igv = valPrecioVenta.subtract(valValorVenta);
            beanEdit.setPrecioSD(valPrecioSd);
            beanEdit.setDescuento(valDescuento);
            beanEdit.setPrecioVenta(valPrecioVenta);
            beanEdit.setValorVenta(valValorVenta);
            beanEdit.setIgv(igv);
            //GWT.log("Index Vista: " + index);
            //index = dataProvider.getList().indexOf(object);
            int indexModel = data.indexOf(object);
            //GWT.log("Index Modelo: " + indexModel);
            data.set(indexModel, beanEdit);
            indexUpdates.add(indexModel);
            context.fire();
            dataProvider.refresh();
            // Update the row and subrow.
            setKeyboardSelectedRow(index, 0, true);
            // Update the column index.
            setKeyboardSelectedColumn(6, true);
        } else {
            Window.alert("escriba un numero");
        }
    }

    private void initEditColumns() {

        precioSd.setFieldUpdater(new FieldUpdater<PrecioItemProxy, String>() {

            @Override
            public void update(int index, PrecioItemProxy object, String value) {
                calcularPrecioSd(index, object, value);
            }
        });

        descuento.setFieldUpdater(
                new FieldUpdater<PrecioItemProxy, String>() {

                    @Override
                    public void update(int index, PrecioItemProxy object, String value
                    ) {
                        calcularDescuento(index, object, value);
                    }
                }
        );
    }

    public CheckCellHead checkAll = new CheckCellHead();
    Header<Boolean> headCheckAll = new Header<Boolean>(checkAll) {

        @Override
        public Boolean getValue() {
            return checkAll.isIsSelected();
        }

        @Override
        public void onBrowserEvent(Cell.Context context,
                Element elem,
                NativeEvent event) {
            if (checkAll.isIsSelected()) {
                checkAll.setIsSelected(false);
                selection(false);
            } else {
                checkAll.setIsSelected(true);
                selection(true);
            }

        }
    };

    private void selection(Boolean select) {
        if (dataProvider.getFilter() != null && !dataProvider.getFilter().isEmpty()) {
            selectionModel.clear();
            for (int i = 0; i < dataProvider.resulted.size(); i++) {
                selectionModel.setSelected(dataProvider.resulted.get(i), select);
            }
        } else {
            selectionModel.clear();
            for (int i = 0; i < data.size(); i++) {
                selectionModel.setSelected(data.get(i), select);
            }
        }
    }

    Column<PrecioItemProxy, Boolean> checkColumn
            = new Column<PrecioItemProxy, Boolean>(new CheckboxCell(true, false)) {
                @Override
                public Boolean getValue(PrecioItemProxy object) {
                    // Get the value from the selection model.
                    return selectionModel.isSelected(object);
                }
            };

    private Column<PrecioItemProxy, Number> valorVenta
            = new Column<PrecioItemProxy, Number>(new NumberCell()) {

                @Override
                public Number getValue(PrecioItemProxy object) {
                    return object.getValorVenta();
                }
            };

    private Column<PrecioItemProxy, Number> igv
            = new Column<PrecioItemProxy, Number>(new NumberCell()) {

                @Override
                public Number getValue(PrecioItemProxy object) {
                    return object.getIgv();
                }
            };

    private Column<PrecioItemProxy, String> precioSd
            = new Column<PrecioItemProxy, String>(new TextInputCell() {
                @Override
                public void render(Cell.Context context, String value, SafeHtmlBuilder sb) {
                    // Get the view data.
                    Object key = context.getKey();
                    TextInputCell.ViewData viewData = getViewData(key);
                    if (viewData != null && viewData.getCurrentValue().equals(value)) {
                        clearViewData(key);
                        viewData = null;
                    }

                    String s = (viewData != null) ? viewData.getCurrentValue() : value;
                    if (s != null) {
                        if (modo.equalsIgnoreCase(GridPrecioItem.E)) {
                            PrecioItemProxy object=(PrecioItemProxy)key;
                            if(object.getEstadoActiva().equalsIgnoreCase("A")){
                            sb.appendHtmlConstant("<input type=\"text\" " + "value=\"" + value + "\" " + " tabindex=\"-1\"></input>");
                            }else{
                                sb.appendHtmlConstant("<input type=\"text\" " + "value=\"" + value + "\" " + " tabindex=\"-1\" DISABLED></input>");
                            }
                        } else if(modo.equalsIgnoreCase(GridPrecioItem.L)){                                                        
                            sb.appendHtmlConstant("<input type=\"text\" " + "value=\"" + value + "\" " + " tabindex=\"-1\" DISABLED></input>");
                        }
                    }
                }
            }) {

                @Override
                public String getValue(PrecioItemProxy object) {
                    return object.getPrecioSD().toString();
                }
            };

    private Column<PrecioItemProxy, String> descuento
            = new Column<PrecioItemProxy, String>(new TextInputCell() {
                @Override
                public void render(Cell.Context context, String value, SafeHtmlBuilder sb) {
                    // Get the view data.
                    Object key = context.getKey();
                    TextInputCell.ViewData viewData = getViewData(key);
                    if (viewData != null && viewData.getCurrentValue().equals(value)) {
                        clearViewData(key);
                        viewData = null;
                    }

                    String s = (viewData != null) ? viewData.getCurrentValue() : value;
                    if (s != null) {
                        if (modo.equalsIgnoreCase(GridPrecioItem.E)) {
                            PrecioItemProxy object=(PrecioItemProxy)key;
                            if(object.getEstadoActiva().equalsIgnoreCase("A")){
                            sb.appendHtmlConstant("<input type=\"text\" " + "value=\"" + value + "\" " + " tabindex=\"-1\"></input>");
                            }else{
                                sb.appendHtmlConstant("<input type=\"text\" " + "value=\"" + value + "\" " + " tabindex=\"-1\" DISABLED></input>");
                            }
                        } else if(modo.equalsIgnoreCase(GridPrecioItem.L)){                                                        
                            sb.appendHtmlConstant("<input type=\"text\" " + "value=\"" + value + "\" " + " tabindex=\"-1\" DISABLED></input>");
                        }
                    }
                }
            }) {

                @Override
                public String getValue(PrecioItemProxy object) {
                    return object.getDescuento().toString();
                }
            };

    private Column<PrecioItemProxy, Number> precioVenta
            = new Column<PrecioItemProxy, Number>(new NumberCell()) {

                @Override
                public Number getValue(PrecioItemProxy object) {
                    return object.getPrecioVenta();
                }
            };

    private Column<PrecioItemProxy, String> estado
            = new Column<PrecioItemProxy, String>(new TextCell()) {

                @Override
                public String getValue(PrecioItemProxy object) {
                    return object.getEstadoActiva();
                }

            };

    private Column<PrecioItemProxy, String> codigo
            = new Column<PrecioItemProxy, String>(new TextCell()) {

                @Override
                public String getValue(PrecioItemProxy object) {
                    return object.getCodigo();
                }

            };

    private Column<PrecioItemProxy, String> marca
            = new Column<PrecioItemProxy, String>(new TextCell()) {

                @Override
                public String getValue(PrecioItemProxy object) {
                    return object.getMarca();
                }

            };

    private Column<PrecioItemProxy, String> descripcion
            = new Column<PrecioItemProxy, String>(new TextCell()) {

                @Override
                public String getValue(PrecioItemProxy object) {
                    return object.getDescripcion();
                }

            };

    private void initStyle() {
        MyResource.INSTANCE.getStlGridData().ensureInjected();
        this.addStyleName(MyResource.INSTANCE.getStlGridData().stlGridData());
    }

    public void setData(List<PrecioItemProxy> data) {
        this.data = data;
        this.setRowCount(data.size(), true);
        this.setRowData(0, data);
        this.setPageSize(data.size());
        dataProvider.setList(data);
        dataProvider.refresh();
        //redraw();
    }

    public List<PrecioItemProxy> getData() {
        return data;
    }

    public SimplePager getPager() {
        return pager;
    }

    @Override
    public MultiSelectionModel<PrecioItemProxy> getSelectionModel() {
        return selectionModel;
    }

    public FilteredListDataProvider<PrecioItemProxy> getDataProvider() {
        return dataProvider;
    }

    public void setModo(String modo) {
        this.modo = modo;
    }

    public HashSet<Integer> getIndexUpdates() {
        return indexUpdates;
    }
       
}


Clase para la seleccion multifila:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.webgocommerce.client.uiutil;

import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;

/**
 *
 * @author SISTEMAS
 */
public class CheckCellHead extends AbstractCell<Boolean> {

    private Boolean isSelected = false;
    private static final SafeHtml INPUT_CHECKED = SafeHtmlUtils.fromSafeConstant("<input type=\"checkbox\" tabindex=\"-1\" checked/>");
    private static final SafeHtml INPUT_UNCHECKED = SafeHtmlUtils.fromSafeConstant("<input type=\"checkbox\" tabindex=\"-1\"/>");

    public CheckCellHead() {
        super("click");
    }

    @Override
    public void render(Context context, Boolean value, SafeHtmlBuilder sb) {
        if (isSelected) {
            sb.append(INPUT_CHECKED);
        } else {
            sb.append(INPUT_UNCHECKED);
        }
    }

    public Boolean isIsSelected() {
        return isSelected;
    }

    public void setIsSelected(Boolean isSelected) {
        this.isSelected = isSelected;
    }
    
    

}


 

Web: Http://company.kiongo.com            

La información contenida en este e-mail es confidencial, privilegiada y está dirigida exclusivamente a su destinatario. Su revisión, difusión, distribución o copiado está prohibido. Si ha recibido este e-mail por error por favor bórrelo y envíe un mensaje al remitente.

The information contained in this e-mail is privileged and confidential and is intended only for its addressee. Any review, dissemination, distribution or copying of this is prohibited. If you have received this mail in error please delete the original message and e-mail us.


2015-02-04 15:36 GMT-05:00 BM <bhushan.madan@gmail.com>:
So I followed the code given in these threads : 

Apparently when I implemented this, it selects the header checkbox and thereby selects all records for every page. 

Here is my requirement :

I have two column cell table. 

First Column : Checkbox for row selection
Second Column : Employee Name

The idea here is for each classroom, the user can go and select certain employees from list of all employees in cell table and save to DB. If the user comes back to the same classroom, the cell table should show all total employee records with the previously selected employees should have their corresponding row checkbox checked. The user can thereby update the selection by checking and unchecking employees and save again. 

This works fine but since we have paging mechanism in cell table I want to implement "Select All" checkbox on header above the First Column and when that is checked, the corresponding row for that page should all be selected. Then if the user paginates to next page, the "Select All" checkbox on header above the First Column for next page should be uncheck now and that next page should show list of employees with corresponding row checkbox checked (previously checked from DB) if any. The user can check that "Select All" checkbox on header to select all the corresponding row for that page and so on. 

The few important things here is, 
1) I do want to show previously checked employees from the DB in the list of total all employees.
2)  "Select All" checkbox on header should be uncheck every time user comes to this screen. 
3) When the user clicks  "Select All" checkbox on header, then only it should select all the rows "for that page only" and not all the records across all the pages. 
3) Clicking next page should show what I described in point 1 and 2 above. 

Any help would be appreciated. 

--
You received this message because you are subscribed to the Google Groups "Google Web Toolkit" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-web-toolkit+unsubscribe@googlegroups.com.
To post to this group, send email to google-web-toolkit@googlegroups.com.
Visit this group at http://groups.google.com/group/google-web-toolkit.
For more options, visit https://groups.google.com/d/optout.

--
You received this message because you are subscribed to the Google Groups "Google Web Toolkit" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-web-toolkit+unsubscribe@googlegroups.com.
To post to this group, send email to google-web-toolkit@googlegroups.com.
Visit this group at http://groups.google.com/group/google-web-toolkit.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment