ParamQuery grid support forum

General Category => Help for ParamQuery Pro => Topic started by: megastream on June 06, 2018, 07:01:39 pm

Title: How to export selected rows from grid
Post by: megastream on June 06, 2018, 07:01:39 pm
Hi,

I am using PqGrid pro version 5.1.0

I want to export selected rows in excel but when i click on Export button, it always download all rows.

I've followed this link

https://paramquery.com/forum/index.php?topic=1524.msg6616#msg6616

to filter the selected rows only but did not get success.

My code is:

Code: [Select]
var $grid = jQuery("#grid_json");
jQuery(document).ready(function(){
    var gridheight = 600;
   
    var pqVS = {
        rpp: 100, //records per page.
        init: function () {
            this.totalRecords = 0;
            this.requestPage = 1; //begins from 1.
            this.data = [];
        }
    };
   
    pqVS.init();
   
    //define common ajax object for addition, update and delete.
    var ajaxObj = {
        dataType: "JSON",
        beforeSend: function () {
            this.showLoading();
        },
        complete: function () {
            this.hideLoading();
        },
        error: function () {
            this.rollback();
        }
    };
   
    var obj = {
        hwrap: false,
        rowBorders: false,
        autoRow: false,
        rowHt: 35,
        trackModel: { on: true }, //to turn on the track changes.
        numberCell: {show: false},
        toolbar: {
            items: [{
                type: 'button',
                label: "Export",
                icon: 'ui-icon-arrowthickstop-1-s',
                listener: function () {
                    /*
                    var ids = this.SelectRow().getSelection().map(function(rowList){
                    return rowList.rowData.ProductID;
                })
               
                alert(ids);
                */
               
                //filter the selected rows.
                $grid.filter({
                    mode: 'AND',
                    oper: 'replace',
                    data: [{dataIndx: 'state', condition: 'equal', value: true}]
                });
               
               
                var format = 'xlsx',
                blob = this.exportData({
                    //url: "http://local.pims/export/exportdata",
                    format: format,
                    render: true
                });
                if(typeof blob === "string"){
                    blob = new Blob([blob]);
                }
                saveAs(blob, "pqGrid."+ format );
               
                //reset the filter.
                $grid.filter({
                    oper: 'replace',
                    data: []
                })
            }
        }
    ]
},
rowSelect: function (evt, ui) {
    var str = JSON.stringify(ui, function(key, value){
        if( key.indexOf("pq_") !== 0){
            return value;
        }
    }, 2)
    $("#rowSelect_pre").html(str);
},

title: "<b>Export Products</b>",
postRenderInterval: -1, //synchronous post render.
swipeModel: { on: false },
selectionModel: { type: 'cell' },
filterModel: { on: true, header: true, type: 'remote' },
resizable: true,
virtualX: true,
virtualY: true,
load: function (evt, ui) {
    var grid = this,
    data = grid.option('dataModel').data;
    grid.widget().pqTooltip(); //attach a tooltip.
},
editable: true,
create: function (evt, ui) {
    this.widget().pqTooltip();
},
sortModel: { type: 'remote', sorter: [{ dataIndx: 'company', dir: 'up'}] },
beforeSort: function (evt) {
    if (evt.originalEvent) {//only if sorting done through header cell click.
        pqVS.init();
    }
},
beforeTableView: function (evt, ui) {
    var initV = ui.initV,
    finalV = ui.finalV,
    data = pqVS.data,
    rpp = pqVS.rpp,
    requestPage;
   
    if (initV != null) {
       
        //if records to be displayed in viewport are not present in local cache,
        //then fetch them from remote database/server.
       
        if (data[initV] && data[initV].pq_empty) {
            requestPage = Math.floor(initV / rpp) + 1;
        }
        else if (data[finalV] && data[finalV].pq_empty) {
            requestPage = Math.floor(finalV / rpp) + 1;
        }
       
        if (requestPage >= 1) {
            if (pqVS.requestPage != requestPage) {
               
                pqVS.requestPage = requestPage;
               
                //initiate remote request.
                this.refreshDataAndView();
            }
        }
    }
}
};

obj.dataModel = {
    dataType: "JSON",
    location: "remote",
    recIndx: "ProductID",
    url: "http://mydemo.com/export/getproductsbyajax",
    postData: function () {
        return {
            pq_curpage: pqVS.requestPage,
            pq_rpp: pqVS.rpp
        };
    },
    getData: function (response) {
        var data = response.data,
        totalRecords = response.totalRecords,
        len = data.length,
        curPage = response.curPage,
        pq_data = pqVS.data,
        init = (curPage - 1) * pqVS.rpp;
       
        if (!pqVS.totalRecords) {
            //first time initialize the rows.
            for (var i = len; i < totalRecords; i++) {
                pq_data[i + init] = { pq_empty: true };
            }
            pqVS.totalRecords = totalRecords;
        }
        for (var i = 0; i < len; i++) {
            pq_data[i + init] = data[i];
            pq_data[i + init].pq_empty = false;
        }
        return { data: pq_data }
    },
    error: function (jqXHR, textStatus, errorThrown) {
        console.log(errorThrown);
    }
};

obj.colModel = [
    {
        dataIndx: "state",
        align: "center",
        "width": "165",
        title: "<label><input type='checkbox' />&nbsp;Select All</label>",
        cb: { header: true, select: true, all: true },
        type: 'checkbox',
        cls: 'ui-state-default',
        dataType: 'bool',
        editor: false
    }
    ,{
        "title": "Column 1",
        "width": "165",
        "editable": false,
        "dataIndx": "catAttr_8",
        "filter": {
            "type": "textbox",
            "condition": "begin",
            "listeners": ["change"]
        },
        "editor": {
            "type": "textbox"
        }
    }
    ,{
        "title": "Column 2",
        "width": "165",
        "editable": false,
        "dataIndx": "catAttr_3",
        "filter": {
            "type": "textbox",
            "condition": "begin",
            "listeners": ["change"]
        },
        "editor": {
            "type": "textbox"
        }
    }
   
   
];

$grid.pqGrid(obj);
$grid.pqGrid( "option", "height", gridheight );

});

Please let me know what i am doing wrong here.

Thanks
Title: Re: How to export selected rows from grid
Post by: paramvir on June 06, 2018, 11:10:39 pm
your code looks incorrect. filter is not a method of jQuery $grid variable but it's a method of grid javascript instance.

Code: [Select]
$grid.filter({
                    mode: 'AND',
                    oper: 'replace',
                    data: [{dataIndx: 'state', condition: 'equal', value: true}]
                });

Please correct $grid variable to this inside the listener.
Title: Re: How to export selected rows from grid
Post by: megastream on June 09, 2018, 11:48:42 am
Hi,

Thanks for your reply but when i do that i got error shown in screenshot.

Please advice.

Thanks
Title: Re: How to export selected rows from grid
Post by: paramvir on June 11, 2018, 06:31:40 am
The error says to correct the filter parameters.

Please correct data parameter name to rules in call to filter method.

https://paramquery.com/pro/api#method-filter
Title: Re: How to export selected rows from grid
Post by: megastream on June 11, 2018, 03:36:45 pm
HI,

Thanks for correcting my mistake.

Now there is no error in console.

Now my code looks like :

Code: [Select]
toolbar: {
            items: [{
                            type: 'button',
                            label: "Export",
                            icon: 'ui-icon-arrowthickstop-1-s',
                            listener: function () {

                            //filter the selected rows.
                            this.filter({
                                mode: 'AND',
                                oper: 'replace',
                                rules: [{dataIndx: 'state', condition: 'equal', value: true}]
                            });

                            var format = 'xlsx',
                            blob = this.exportData({
                                format: format
                                render: true
                            });
                            if(typeof blob === "string"){
                                blob = new Blob([blob]);
                            }
                            saveAs(blob, "pqGrid."+ format );
                    }
                }
            ]
        }

But still when i click on export, it downloads all the data from grid not the selected row.

Also it hits the server URL to get data. Although I've not used URL parameter in exportData() method. Why it is going to server and why there is all rows in exported excel instead of selected ones.

Please help me in this.

Many thanks in advance.
Title: Re: How to export selected rows from grid
Post by: megastream on June 11, 2018, 03:57:19 pm
Please consider , (comma) in these lines of code between format and render properties:

Code: [Select]
blob = this.exportData({
                                format: format
                                render: true
                            });

as I've comma after format: format in my code but missed it in posted code.

Sorry for inconvenience.

Thanks
Title: Re: How to export selected rows from grid
Post by: paramvir on June 12, 2018, 10:55:26 am
It's exporting whole data and hitting remote url because of remote filtering. Remote filtering is async, so the code execution goes to next line which is exportData, thus exporting whole data.

Please set filterModel.type = "local" just before filtering and reset it to remote.

this.option('filterModel.type', "local");

Then

//filter
//export
//reset filter to empty.
//reset filterModel.type to 'remote'
Title: Re: How to export selected rows from grid
Post by: megastream on June 12, 2018, 05:57:05 pm
Hi,

Thank you so much for helping me to figure out the issues.

Now it is working fine.

This is how i am resetting filter:

Code: [Select]
this.filter({
    oper: 'replace',
    rules: []
});

Correct me if i am wrong?

Also can you please guide me, How can i exclude checkbox column in exported excel file?

Many thanks again.

You are awesome!
Title: Re: How to export selected rows from grid
Post by: paramvir on June 13, 2018, 09:26:37 am
Resetting filter looks fine. There is also reset method in the API.

Any column can be excluded in the exported file by adding copy:false property to the column.

https://paramquery.com/pro/api#option-column-copy
Title: Re: How to export selected rows from grid
Post by: megastream on June 13, 2018, 10:26:20 am
Hi,

Your solutions is working correctly.

Now all things working fine.

Thank you so much  :)

Cheers