Execute batchSave in ej2 childgrid

How can I run batchSave in  ej2 childgrid?

16 Replies

MA Marko August 15, 2018 04:03 PM UTC

Hi,

I did this in the following way:

HTML:
<ejs-grid
#Grid
...
TS:
@ViewChild('Grid')
Grid: GridComponent;

save() {
this.Grid.endEdit();
}

Regards,
Marko


RS Renjith Singh Rajendran Syncfusion Team August 15, 2018 04:18 PM UTC

Hi Timothy, 

Thanks for contacting Syncfusion support. 

In Essential JS2, we have defined the separate modules for Grid actions such as Paging, grouping, Editing and filtering. You can run the ‘batchSave’ by using the following codes. Please refer to the following code example for your convenience, 


      let childgridObj = document.getElementById("Grid").ej2_instances[0];   //Child Grid instance 
      childgridObj.editModule.batchSave();        //calling the batchSave API 


 
Please get back to us if you need further assistance. 

Regards, 
Renjith Singh Rajendran. 



TP Timothy Pang August 16, 2018 04:13 AM UTC

Dear all,

Thanks for your quick response and the help.
Marko, since I'd like to save the data in the child grid, not the main grid, your code may not suitable.

Renjith, when I tried the code you provided, an error occurred. The details is shown as below:

ERROR TypeError: Cannot read property 'ej2_instances' of null
    at DamageComponent.webpackJsonp.1120.DamageComponent.save (damage.component.ts:257)
    at Object.eval [as handleEvent] (DamageComponent.html:4)
    at handleEvent (core.es5.js:12023)
    at callWithDebugContext (core.es5.js:13493)
    at Object.debugHandleEvent [as handleEvent] (core.es5.js:13081)
    at dispatchEvent (core.es5.js:8615)
    at core.es5.js:10783
    at SafeSubscriber.schedulerFn [as _next] (core.es5.js:3647)
    at SafeSubscriber.__tryOrUnsub (Subscriber.js:238)
    at SafeSubscriber.next (Subscriber.js:185)

It seems that document.getElementById("Grid") returns nothing.





HJ Hariharan J V Syncfusion Team August 17, 2018 12:03 PM UTC

Hi Timothy, 
Thanks for your update. 

We have validated the provided information and in our previous update we have demonstrate to get the instance of the child grid and based on the child grid instance you can perform the batchSave operation in Grid. We suspect in your sample you are not using “Grid “as id for the child grid so that it cause the reported problem.  

We have created a sample for your reference. In the below sample, we have performed the batchSave operation in button click event. Kindly refer to the below code example and sample for more information.   

import { DetailRowService, GridModel, Grid } from '@syncfusion/ej2-ng-grids'; 
 
@Component({ 
    selector: 'app-container', 
    template: ` <button id='show' ej-button class='e-flat' (click)='show()'> BatchSave </button> 
    <ejs-grid #grid [dataSource]='pData' height='265px' [childGrid]='childGrid' [showColumnChooser]= 'true'> 
              <e-columns> 
                    <e-column field='City' headerText='City' width=150></e-column> 
              </e-columns> 
                </ejs-grid> 
                `, 
    providers: [DetailRowService] 
}) 
export class AppComponent implements OnInit { 
    public childGrid: GridModel = { 
        queryString: 'EmployeeID', 
        editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true, mode: 'Batch', showConfirmDialog: false, }, 
        toolbar: ['Edit', 'Update', 'Cancel'], 
        columns: [ 
            { field: 'OrderID', headerText: 'Order ID', width: 120, isPrimaryKey: true }, 
        ] 
    }; 
 
    ngOnInit(): void { 
        this.pData = employeeData; 
    } 
 
    show() { 
        // you can also get the child grid instances as like below  
        const childGridObj: Grid = (document.querySelector('.e-grid .e-grid') as any).ej2_instances[0]; 
        childGridObj.editModule.batchSave(); // perform batchSave 
    } 
} 




Please get back to us if you need further assistance. 

Regards,
Hariharan 



TP Timothy Pang August 20, 2018 01:37 AM UTC

Hi Hariharan,

Thanks for your help. I've tested your code. But I found that only the first child grid can save the changes. Other changes in another child grids cannot be saved. Can you show me how to save all the changes in the main grid and all child grids? Thanks!


HJ Hariharan J V Syncfusion Team August 20, 2018 11:19 AM UTC

Hi Timothy, 
Thanks for your update. 

We have analyzed your requirement and created a sample based for your requirement. In the below sample, We have perform batchSave operation for all grids (Main and child grid) in the button click event. You can also achieve your requirement by using the below way. 

Kindly refer to the below code example and sample for more information. 

 
@Component({ 
    selector: 'app-container', 
    template: ` <button id='show' ej-button class='e-flat' (click)='show()'> BatchSave </button> 
    <ejs-grid #grid [dataSource]='pData' height='265px' [childGrid]='childGrid' [showColumnChooser]= 'true' [editSettings]='editSettings' [toolbar]='toolbar'> 
    <e-columns> 
         <e-column field='EmployeeID' headerText='Employee ID' textAlign='Right' isPrimaryKey='true'width=120></e-column> 
                    </e-columns> 
                </ejs-grid> 
                `, 
    providers: [DetailRowService] 
}) 
export class AppComponent implements OnInit { 
    public childGrid: GridModel = { 
        queryString: 'EmployeeID', 
        . . . . . 
    }; 
    ngOnInit(): void { 
        this.pData = employeeData; 
    } 
 
    show() { 
        // get all the grid and perform the batchSave operation  
        for (let i = 0; i < document.querySelectorAll('.e-grid').length; i++) { 
            let gridObj: Grid = document.querySelectorAll('.e-grid')[i].ej2_instances[0].editModule.getBatchChanges(); 
            // batchSave called only when perform CRUD operation (avoid duplicate request)  
            if (gridObj.addedRecords.length || gridObj.changedRecords.length || gridObj.deletedRecords.length) { // check whether grid has been edited 
                (document.querySelectorAll('.e-grid')[i] as any).ej2_instances[0].editModule.batchSave(); 
            } 
        } 
    } 
} 

  

Please get back to us if you need further assistance. 

Regards,
Hariharan 



TP Timothy Pang August 21, 2018 03:38 AM UTC

Hi Hariharan,

Thanks a lot. You help me to solve the problem.

But I'd like to ask one more question. In the grid, we have checkbox and we write some codes to trigger the changes of checkbox state. Then user can save all the changes by clicking "Save" button. But when we'd like to get all the changes of the date by calling "this.grid..editModule.getBatchChanges() as any).changedRecords.length" in the save function, we get 0. Please help me to solve this problem. Thanks!!

I provide the code snippet for your reference.


import { DetailRowService, GridModel, Grid } from '@syncfusion/ej2-ng-grids'; 

@Component({ 
    selector: 'app-container', 
    template: `
               ....
               <ej2-grid ...>
               <e-columns>
               ....
                    <e-column field='isVerified' type='boolean'>
                         <ng-template  #template let-data>
                               <ejs-checkbox #checkbox [checked]='data.isVerified' (change)='checkboxChange($event)'></ejs-checkbox>
                         </ng-template>
                    </e-column>
               ....
              `, 
    providers: [DetailRowService] 
}) 
export class AppComponent implements OnInit {

           @ViewChild('grid')
           public grid: GridComponent;
           ...    
     checkboxChange(args: ChangeEventArgs) {
        let currentRowObject: any = this.grid.getRowObjectFromUID(this.rowID);
        let currentRowData: Object = currentRowObject.data;
       
        currentRowData["isVerified"] = args.checked;
                this.grid.setCellValue(currentRowData["jobUid"], "isVerified", args.checked);
        currentRowObject.changes = currentRowData;
    }

    save() {
        var ch: any = (this.grid.editModule.getBatchChanges() as any).changedRecords.length;   => always return 0??
        ...
    }
}


are you



LR Logesh Rajappa Syncfusion Team August 22, 2018 11:17 AM UTC

Hi Timothy, 

Thanks for contacting Syncfusion support. 
 
Query : But when we'd like to get all the changes of the date by calling "this.grid..editModule.getBatchChanges() as any).changedRecords.length" in the save function, we get 0 
 
We have analyzed your query and we suspect that you are saving the grid record changes in your custom function using setCellValue method instead of updating it. Saved records will not be available in changedRecords property of the editModule. So we have used updateCell to update the cell values and in your custom save function the changed records will be available for you to proceed further. Please find the below sample and documentation for your reference, 

Code Example

[.ts] 
... 
@Component({ 
    selector: 'app-container', 
    template: ` <button id='show' ej-button class='e-flat' (click)='save()'> BatchSave </button> 
    <ejs-grid #grid [dataSource]='data' height='265px' [editSettings]='editSettings' [toolbar]='toolbar'> 
                    <e-columns> 
                        ... 
                        <e-column field='Verified' type='boolean'> 
                        <ng-template  #template let-data> 
                               <ejs-checkbox #checkbox [checked]='data.Verified' (change)='checkboxChange($event)'></ejs-checkbox> 
                         </ng-template> 
                    </e-column>  
                    </e-columns> 
                </ejs-grid> 
                `, 
    providers: [] 
}) 
export class AppComponent implements OnInit { 
... 
    checkboxChange(args: ChangeEventArgs) { 
        let currentRowObject: any = this.grid.getRowObjectFromUID(args.event.target.closest('tr').getAttribute('data-uid')); 
        let currentRowData: Object = currentRowObject.data; 
         
        //currentRowData["Verified"] = args.checked;    //updating the datasource the changes so we will not get the changed records 
        //this.grid.setCellValue(currentRowData["jobUid"], "isVerified", args.checked); // setCellValue also saves the changes 
        let rowIndex: any = args.event.target.closest('td').getAttribute("index");   
        this.grid.editModule.updateCell(rowIndex, "Verified", args.checked);  //so we updating the changes instead of saving it 
    } 
    save() { 
        var ch: any = (this.grid.editModule.getBatchChanges() as any).changedRecords.length; //Now you will get the changed records here 
        alert(ch); 
    } 
    ngOnInit(): void { 
        this.data = data, 
          this.editSettings = { allowEditing: true, allowAdding: true, allowDeleting: true, mode: 'Batch', showConfirmDialog: false }; 
        this.toolbar = ['Edit', 'Update', 'Cancel']; 
    } 
} 
 
 

Please get back to us for further assistance. 

Regards, 
Logesh Rajappa


TP Timothy Pang August 24, 2018 02:13 AM UTC

Dear Logesh Rajappa,

Sorry for late reply.
After I used your code, an exception occurred as follows:


XXXXComponent.html:133 ERROR TypeError: Cannot read property 'index' of undefined
    at CellRenderer.evaluate (ej2-grids.es5.js:3918)
    at CellRenderer.refreshCell (ej2-grids.es5.js:4001)
    at CellRenderer.refreshTD (ej2-grids.es5.js:3967)
    at BatchEdit.refreshTD (ej2-grids.es5.js:20275)
    at BatchEdit.updateCell (ej2-grids.es5.js:20239)
    at Edit.updateCell (ej2-grids.es5.js:20652)
    at XXXXComponent.webpackJsonp.1132.XXXXComponent.checkboxChange (xxxx.component.ts:181)
    at Object.eval [as handleEvent] (XXXXComponent.html:133)
    at handleEvent (core.es5.js:12023)
    at callWithDebugContext (core.es5.js:13493)

Can you help me to solve it? Thanks!

Timothy




HJ Hariharan J V Syncfusion Team August 24, 2018 09:08 AM UTC

Hi Timothy, 

Thanks for contacting Syncfusion support. 
 
Query : After I used your code, an exception occurred as follows: XXXXComponent.html:133 ERROR TypeError: Cannot read property 'index' of undefined 
 
We have analyzed your query and we are unable to reproduce the reported issue in the sample we provided in last update. So please share the below information or details, it will help us provide better solution as soon as possible.  

  1. Are you using provided code in any custom function other than checkboxChange? If yes, please provide details about it.
  2. Please provide full grid code sample.
  3. Please reproduce the reported issue in the provided sample if possible.

Regards, 
Hariharan 



TP Timothy Pang August 24, 2018 10:02 AM UTC

Hi Hariharan ,

Thanks for your quick response.

1. I only add the code in checkboxChange event handler.

I found the error comes from ej2.grids.es5.js line 3913-3927:
    CellRenderer.prototype.evaluate = function (node, cell, data, attributes$$1, fData) {
        var result;
        if (cell.column.template) {
            var literals = ['index'];
            var dummyData = extend({}, data, (_a = {}, _a[foreignKeyData] = fData, _a));
            result = cell.column.getColumnTemplate()(extend({ 'index': attributes$$1[literals[0]] }, dummyData), this.parent, 'template');
            appendChildren(node, result);
            result = null;
            node.setAttribute('aria-label', node.innerText + ' is template cell' + ' column header ' +
                cell.column.headerText);
            return false;
        }
        return true;
        var _a;
    };

It seems that the parameter attributes$$1 is null. When I trace back the call stack, attributes$$1 comes from the highlighted function call.

    BatchEdit.prototype.refreshTD = function (td, column, rowObj, value) {
        var cell = new CellRenderer(this.parent, this.serviceLocator);
        this.setChanges(rowObj, column.field, value);
        var frzCols = this.parent.getFrozenColumns();
        refreshForeignData(rowObj, this.parent.getForeignKeyColumns(), rowObj.changes);
        cell.refreshTD(td, rowObj.cells[this.getCellIdx(column.uid) - (this.getCellIdx(column.uid) >= frzCols ? frzCols : 0)], rowObj.changes);
        td.classList.add('e-updatedtd');
        this.parent.notify(toolbarRefresh, {});
    };

Here the highlighted call only pass 3 parameters to refreshTD but attributes$$1 is the forth parameter.

Can you help me to solve this? Thanks!











HJ Hariharan J V Syncfusion Team August 27, 2018 10:28 AM UTC

Hi Timothy, 
 
Thanks for your update. 
 
We have created a new incident under your account to follow up with this query. We suggest you follow up the incident for further updates using your direct trac account.  
 
Regards, 
Hariharan 



TP Timothy Pang August 28, 2018 01:10 AM UTC

Hi Hariharan,

OK. If you need any information, I'll provide it as soon as possible. Thanks!!


HJ Hariharan J V Syncfusion Team August 28, 2018 06:56 AM UTC

Hi Timothy,  
  
Thanks for your update.  
  
We suggest you to follow-up the newly created incident for further details. 
  
Regards,  
Hariharan  



TP Timothy Pang August 29, 2018 07:31 AM UTC

Hi all,

Now the error is fixed after updating to the latest version. Thanks a lot.

But after saving the changes and refresh the data, it shows no row in the grid and the pager shows that there are items.
I find that when executing "this.grid.editModule.updateCell(rowIndex, field, args.checked)" in the checkboxChange event, the data is disappeared after refresh.

Can you help me to solve this problem? Thanks!


HJ Hariharan J V Syncfusion Team September 6, 2018 01:24 PM UTC

Hi Timothy, 

Thanks for your update. 

We have created a new incident under your account to follow up with this query. We suggest you follow up the incident for further updates using your direct trac account.  
 
  

Regards, 
Hariharan 


Loader.
Up arrow icon