We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

Batch mode: Delete specific records manually

Hi,

Goal: Delete the specific records in Grid, which selected by some criteria. 

Description: 

Columns definition:
columns: [
    { field: 'id', headerText: 'ID', width: 30, visible: false, showInColumnChooser: false, isPrimaryKey: true },
{ field: 'profileId', foreignKeyField: 'profileId', foreignKeyValue: 'profileName', dataSource: that.usersDS, headerText: 'User Name', width: 90, visible: true, showInColumnChooser: false,},
{ field: 'wageTypeStartTime', headerText: 'Date', width: 100, format: { type:'date', format:'ccc dd.MM.yyyy' }, editType: 'datepickeredit', edit: { params: { format:'dd.MM.yyyy' }} },
{ field: 'wageTypeEndTime', headerText: 'End time', width: 200, visible: false, showInColumnChooser: false },
{ field: 'wageTypeId', foreignKeyField: 'wageTypeId', foreignKeyValue: 'wageTypeName', dataSource: that.wageTypesDS, headerText: 'Wage Type', width: 90, visible: true, showInColumnChooser: false },
    { field: 'quantity', headerText: 'Quantity', editType: 'numericedit', format: 'N2', width: 50 },
{ field: 'multiplier', headerText: 'Multiplier', editType: 'numericedit', format: 'N3', visible: true, width: 50},
{ field: 'value', headerText: 'Value', editType: 'numericedit', format: 'C2', width: 50 },
{ field: 'amount', headerText: 'Amount', format: 'C2', allowEditing: false, width: 50 },
{ field: 'comment', headerText: 'Comment', visible: false, width: 100 },
{ field: 'status', headerText: 'Status', width: 50, valueAccessor: that.statusFormatter, allowEditing: false },
{ headerText: 'Actions', width: 60,
commands: [{ type: 'EditCustom', buttonOption: { iconCss: 'fa fa-payroll-edit fa-pencil', cssClass: 'e-flat', click: that.editItemCommand } },
{ type: 'Delete', buttonOption: { iconCss: 'fa fa-payroll-delete fa-trash', cssClass: 'e-flat' } },
{ type: 'Save', buttonOption: { iconCss: 'e-icons e-update', cssClass: 'e-flat' } },
{ type: 'Cancel', buttonOption: { iconCss: 'e-icons e-cancel-icon', cssClass: 'e-flat' } },
{ type: 'Approve', buttonOption: { iconCss: 'fa fa-payroll-approve fa-thumbs-o-up', cssClass: 'e-flat', click: that.approveItemCommand } },
{ type: 'Disapprove', buttonOption: { iconCss: 'fa fa-payroll-disapprove fa-thumbs-o-down', cssClass: 'e-flat', click: that.disapproveItemCommand } },
{ type: 'Revoke', buttonOption: { iconCss: 'fa fa-payroll-revoke fa-undo', cssClass: 'e-flat', click: that.revokeItemCommand } } ]
},
{ type: 'checkbox', allowFiltering: false, allowSorting: false, width: 50 },
],


Toolbar definition:
toolbar: [ 'Add',
{ text: 'Edit', tooltipText: 'Edit', id: 'Grid_edit', template: '<button class="e-tbar-btn e-tbtn-txt e-control e-btn e-lib" type="button" id="Grid_edit" tabindex="-1" style="width: auto;"><span class="e-btn-icon e-edit e-icons e-icon-left"></span><div class="e-tbar-btn-text">Edit</div><span class="e-tbar-selitems-counter"></span></button>' },
{ text: 'Delete', tooltipText: 'Delete', id: 'Grid_delete_custom', template: '<button class="e-tbar-btn e-tbtn-txt e-control e-btn e-lib" type="button" id="Grid_delete_custom" tabindex="-1" style="width: auto;"><span class="e-btn-icon e-delete e-icons e-icon-left"></span><div class="e-tbar-btn-text">Delete</div><span class="e-tbar-selitems-counter"></span></button>' },
{ text: 'Approve', tooltipText: 'Apporve', prefixIcon: 'fa fa-thumbs-o-up', id: 'approve_toolbar', template: '<button class="e-tbar-btn e-tbtn-txt e-control e-btn e-lib" type="button" id="approve_toolbar" tabindex="-1" style="width: auto;"><span class="fa fa-thumbs-o-up"></span><div class="e-tbar-btn-text">Approve</div><span class="e-tbar-selitems-counter"></span></button>' },
{ text: 'Disapprove', tooltipText: 'Unapporve', prefixIcon: 'fa fa-thumbs-o-down', id: 'disapprove_toolbar', template: '<button class="e-tbar-btn e-tbtn-txt e-control e-btn e-lib" type="button" id="disapprove_toolbar" tabindex="-1" style="width: auto;"><span class="fa fa-thumbs-o-down"></span><div class="e-tbar-btn-text">Disapprove</div><span class="e-tbar-selitems-counter"></span></button>' },
{ text: 'Revoke', tooltipText: 'Revoke', prefixIcon: 'fa fa-undo', id: 'revoke_toolbar', template: '<button class="e-tbar-btn e-tbtn-txt e-control e-btn e-lib" type="button" id="revoke_toolbar" tabindex="-1" style="width: auto;"><span class="fa fa-undo"></span><div class="e-tbar-btn-text">Revoke</div><span class="e-tbar-selitems-counter"></span></button>' },
{ text: 'PdfExport', tooltipText: 'PdfExport', id: 'Grid_pdfexport', template: '<button class="e-tbar-btn e-tbtn-txt e-control e-btn e-lib" type="button" id="Grid_pdfexport" tabindex="-1" style="width: auto;"><span class="e-btn-icon e-pdfexport e-icons e-icon-left"></span><div class="e-tbar-btn-text">Save PDF</div></button>' },
{ text: 'ExcelExport', tooltipText: 'ExcelExport', id: 'Grid_excelexport', template: '<button class="e-tbar-btn e-tbtn-txt e-control e-btn e-lib" type="button" id="Grid_excelexport" tabindex="-1" style="width: auto;"><span class="e-btn-icon e-excelexport e-icons e-icon-left"></span><div class="e-tbar-btn-text">Save Excel</div></button>' },
{ text: 'CsvExport', tooltipText: 'CsvExport', id: 'Grid_pdfexport', template: '<button class="e-tbar-btn e-tbtn-txt e-control e-btn e-lib" type="button" id="Grid_csvexport" tabindex="-1" style="width: auto;"><span class="e-btn-icon e-csvexport e-icons e-icon-left"></span><div class="e-tbar-btn-text">Save CSV</div></button>' },
{ text: 'Update', tooltipText: 'Update', cssClass: 'display-always', id: 'Grid_update' },
{ text: 'Cancel', tooltipText: 'Cancel', cssClass: 'display-always', id: 'Grid_cancel' },
],


To achieve this goal, I used the "deleteRecord" method inside the toolbar click event handler, but it works wrong -- that deletes all selected rows/records in Grid, and I need to delete rows that match the filter creteria even if I selected all rows in grid:

gridToolbarClick : function(args){
     if(args['item']['properties'].id === 'Grid_delete_custom') {
      var selectedRows = grid.getSelectedRecords().filter(it => it.status == 0 || it.status == 1 || it.status == 2);
     selectedRows.forEach((element) => {
     grid.deleteRecord("id", element);
     console.log(element);
     });
  }
}


I'll be very appreciate if you help me to resolve this issue. Thanks!






7 Replies

TS Thavasianand Sankaranarayanan Syncfusion Team April 17, 2019 06:13 AM UTC

Hi Mladen, 

Greetings from Syncfusion support. 

We can achieve your requirement using the toolbarClick event and deleteRecord method of Grid. 

Refer the below code example. 

[index.js] 

ej.base.enableRipple(true); 
 
    var grid = new ej.grids.Grid({ 
        dataSource: window.orderDataSource, 
        editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true, mode: 'Normal', newRowPosition:'Top' }, 
        allowPaging: true, 
        allowSelection: true, 
        selectionSettings: { type: 'Multiple' }, 
        pageSettings: { pageCount: 5 }, 
        toolbar: ['Add', 'Edit', 'Delete', 'Update', 'Cancel'], 
        toolbarClick: toolbarClick, 
        columns: [ 
            { 
                field: 'OrderID', isPrimaryKey: true, headerText: 'Order ID', textAlign: 'Right', 
                validationRules: { required: true, number: true }, width: 140 
            }, 
             
            ---- 
 
        ], 
    }); 
    grid.appendTo('#Grid'); 
 
    function toolbarClick(args){ 
 
      if(args.item.text == "Delete"){ 
 
        args.cancel = true; // To prevent the further action done by toolbarclick event 
        var selectedRows = grid.getSelectedRecords().filter(it => it.ShipCountry == "France" || it.ShipCountry == "Belgium" || it.ShipCountry == "Brazil"); 
           selectedRows.forEach((element) => { 
             grid.deleteRecord("OrderID", element);  
             console.log(element); 
           }); 
      } 
    } 


We have prepared a simple sample in the following stackblitz link. 


Refer the help documentation. 



Regards, 
Thavasianand S. 



ML Mladen Lakic April 17, 2019 01:46 PM UTC

Hi, Thavasianand

Thanks for your response. 
I did everything like in your example, but this does not work for me. I can't understand what's wrong.
 
I managed to solve that problem as follows:

        // Delete
if(args['item']['properties'].id === 'Grid_delete') {
args.cancel = true;

var selectedRows = grid.getSelectedRecords().filter(it => it.Status == 0 || it.Status == 1 || it.Status == 2);
grid.clearSelection(); // clear selection
grid.selectRow(0);     // select 1st row
selectedRows.forEach((element) => {
grid.deleteRecord("Id", element);
console.log(element);
});
}


GS Gurupriyadharshini Sankaranarayanan Syncfusion Team April 18, 2019 08:07 AM UTC

Hi Mladen, 
Thanks for your update. 
Query: I did everything like in your example, but this does not work for me. I can't understand what's wrong. 
We have checked your query and viewed your code that is given in the screenshot. We have found that you have used improper “id” name, may the cause of the issue. We suggest you to use proper id name within the if statement. Please find the below code and sample link for your reference. 
[index.js] 
function toolbarClick(args){ 
      if(args['item']["properties"].id == "Grid_delete_custom"){ 
        args.cancel = true; 
        .  .  .  . 
           }); 
      } 
    } 
  
If you still facing the same issue, Please share the below details to provide better solution. 
  1. Please share your Full Grid code.
  2. Share the screenshot of developer tool console to check script error if any.
 
Regards, 
Gurupriyadharshini S. 



ML Mladen Lakic April 18, 2019 08:43 AM UTC

Hi Gurupriyadharshini, 

Thanks for your response!

Regarding 'id', I just changed it to default - 'Grid_delete', because of I thought, the problem was in that, but it didn't help. Perhaps the problem is in data, I don't use all properties for fields and some of them has null values?

Here is piece of my grid Data Source:




KM Kuralarasan Muthusamy Syncfusion Team April 19, 2019 01:02 PM UTC

Hi Mladen, 

From your screenshot we found that you have incorrectly mentioned the field name “stauts” in the filter method. In your screenshot shows the field name like “status” (First letter is in small). But in the filter method condition you have used field name like “Status” (First letter is in caps). We suspect that this letter case is caused this issue. So please change the filter method condition like as following code and ensure the issue, 

var selectedRows = grid.getSelectedRecords().filter(it => it.status == 0 || it.status == 1 || it.status == 2); 

Please share your full Grid code still if you facing the same issue. 

Regards, 
Kuralarasan M 



ML Mladen Lakic April 22, 2019 07:06 AM UTC

Hi, Kuralarasan

Thanks for response. No, problem definitely not in that. It happened, because of I copied code from my test environment where I have 'Status' field start with upper letter. Unfortunately, I cannot leave all our production code here.

So because of, I don't have time and ideas how to solve it, I trying to get around this problem by the following way: 
1) filter selected rows by specific criteria
2) clear selection
3) get added and existed rows (I do it by is_manual property, which I set to true when I adding new record in Batch mode (on grid.beforeBatchSave event fired)
4) in the 1st foreach I go through added items array and select each row, step by step and after foreach I call the deleteRecord without params.
5) clear selection
6) in the 2nd foreach I go through existed items array and do the same as in 4th point.

But it also doesn't work correctly when I should to delete added and existed items at the same time but deselect some added items  (see attached video). It works fine when I should to delete all added and existed rows.

// Delete
if(args['item']['properties'].id === 'Grid_delete') {
args.cancel = true;
var deletedRows = grid.getSelectedRecords().filter(it => it.status == 0 || it.status == 1 || it.status == 2);
grid.clearSelection();

var batchAddedRows = deletedRows.filter(it => it.is_manual);
var existedRows = deletedRows.filter(it => it.is_manual == undefined);

// delete new rows (added in batch mode)
if(batchAddedRows.length) {
batchAddedRows.forEach((element) => {
var rowIndex = anfPayrollCalculation.getAriaRowIndexByPrimaryKey(element.id);
grid.selectRow(rowIndex);
});
grid.deleteRecord();
grid.clearSelection();
}

// delete existed rows (saved rows)
existedRows.forEach((element) => {
// var rowIndex = grid.getRowsObject().find(item => item.data.id == element.id).index; // find index of deleted row:
var rowIndex = grid.getRowIndexByPrimaryKey(element.id);
grid.selectRow(rowIndex); // select row
});
grid.deleteRecord();


Attachment: delete_problem_67361c0b.zip


TS Thavasianand Sankaranarayanan Syncfusion Team April 24, 2019 10:58 AM UTC

Hi Mladen, 

From your code we found that you need to filter the selected rows from Grid and perform the delete action for that filtered selected rows. We suggest to use selectRows method instead of using selectRow to achieve this requirement. Please use the selectRows method like as following way to achieve this requirement, 

function toolbarClick(args) { 
        if (args['item']["properties"].id == "Grid_delete") { 
            args.cancel = true; 
            var gridObj = document.getElementsByClassName('e-grid')[0].ej2_instances[0]; 
            var selectedRowIndexes = grid.getSelectedRowIndexes(); // Get seleted rows index 
            grid.clearSelection(); 
            var RowsIndex = []; 
            for (var i = 0; i < selectedRowIndexes.length; i++) { 
                var rowObj = grid.getRowsObject()[selectedRowIndexes[i]]; // Get the selected row object based on the selected index 
                if (rowObj.data.CustomerID == null || rowObj.data.CustomerID == "VINET" || rowObj.data.CustomerID == "HANAR" || rowObj.data.CustomerID == "TOMSP") { // Applied the filter for each rows 
                    RowsIndex.push(selectedRowIndexes[i]);  // Stored the rows index if its getting filtered 
                } 
            } 
            grid.selectRows(RowsIndex); // Select all filtered rows based on the stored index 
            grid.deleteRecord()  // Delete the total selected records 
        } 
    } 

We have prepared the sample with this code and you can find that code from the below link, 


Regards, 
Thavasianand S. 


Loader.
Live Chat Icon For mobile
Up arrow icon