ui-grid icon indicating copy to clipboard operation
ui-grid copied to clipboard

[ui-grid 3.0.0-rc.16] Not all rows get flushed when called "flushDirtyRows" on newly created rows

Open pmariduena opened this issue 12 years ago • 12 comments

Hi. Whenever I call "flushDirtyRows(grid)", not all (only the most recently) newly added row is resolved/committed (though all row added rows appear in the "dirty" array from the API before the save). I think this is a bug in handling a "batch" of saves invoked manually by calling flushDirtyRows.

My use case is a ui-grid (loosely based on tutorial 205), with an Add Rows and Save Rows button. rowEditWaitInterval = -1, so that changes are not committed until the user explicitly hits "Save Rows".

We add rows by clicking "Add Rows", and inserting (with $scope.gridOptions.data.unshift({...a blank row...}). Each "blank row" is rowEquality unique, since I am appending a integer suffix that increments on each add.

According to my debug output, each time I add a row, it does end up in the "dirtyRows" array, as long as I edit it, and this works as expected. I add 3 new rows, and I see all 3 new rows in the debug output of the array $scope.gridApi.rowEdit.getDirtyRows($scope.gridApi.grid);

When I press "Save Rows", I then make a PUT $resource call to save the batch of new rows from the Request Body. That works as expected. In the same method, I finally call:

$scope.gridApi.rowEdit.flushDirtyRows($scope.gridApi.grid);

to resolve all the promises, but I end up with the following error message for all but the last added row: entered the saveRowBatch callback to save to server with a rowEntity. That row is: row1-newrow finished mocking server response. success finished calling update

A promise was not returned when saveRow event was raised, either nobody is listening to event, or event handler did not return a promise angular.js:10072 (anonymous function) angular.js:10072 s.logError ui-grid.js:8917 (anonymous function) ui-grid.js:16217 (anonymous function) ui-grid.js:16354 forEach angular.js:325 service.flushDirtyRows ui-grid.js:16353 publicApi.methods.rowEdit.flushDirtyRows ui-grid.js:16138 (anonymous function) ui-grid.js:8375 $scope.saveRows myController.js:286 (anonymous function) angular.js:10847 callback angular.js:19136 Scope.$eval angular.js:12702 Scope.$apply angular.js:12800 (anonymous function) angular.js:19141 jQuery.event.dispatch jquery.js:5095 elemData.handle

Notice we report success in the callback, but also report error.

After processing continues, I see that the flushDirtyRows array from the API still has all but the last added row in the array :/

Can you please look into your flushDirtyRows method, and see if it can properly handle a batch flush of rows?

pmariduena avatar Nov 24 '14 18:11 pmariduena

Here's the code snippet:

        // invoked from UI
        // save one or more row updates (PUT) and commits one or more new rows (POST)
        $scope.saveRows = function() {
            // returns an array of gridRows that are currently dirty.
            var modifiedGridRows = $scope.gridApi.rowEdit.getDirtyRows($scope.gridApi.grid);
            var arrayOfNewRowsInJSON = [];
            // compile a list of rows that have been added (not modified, existing rows)
            angular.forEach(modifiedGridRows, function(gridRow) {
                var currentRowKey = $scope.gridOptions.getRowIdentity(gridRow.entity);
                if("_newRow" in gridRow.entity && "_newRowId" in gridRow.entity) {
                    // remove marker key, as we don't want to serialize this back to the server
                    delete gridRow.entity._newRow;
                    // REMOVE newRowId key suffix, since server also doesn't support this
                    delete gridRow.entity._newRowId;
                    this.push(gridRow.entity);
                }
            }, arrayOfNewRowsInJSON);

            if(arrayOfNewRowsInJSON.length > 0) {
                var results2 = rowService.addRows(arrayOfNewRowsInJSON);
                results2.$promise.then(function (response) {
                    $log.log('Successfully added new row(s). Response is: ' + angular.toJson(response));
                    // reset internal list of newly added rows (list kept mainly for debug)
                    $scope.newRowsToBeSaved = [];
                }, function (httpResponse) {
                    $log.error('Failed to add the new row: httpResponse is: ' + angular.toJson(httpResponse));
                });
            }

            // Done with adds and modifies, so, we now trigger the framework to resolve the promises
            // on all the modified and new rows (so the rows states go from isSaving to clean).
            $scope.gridApi.rowEdit.flushDirtyRows($scope.gridApi.grid);
            $log.log('Exit saveRows() method');

}; ...

        // a saveRowBatch event callback definition: marks rows that are saved as resolved
        // so they don't appear greyed out or red on the ui-grid. Required by the API.
        $scope.saveRowBatch = function(rowEntity) {
            $log.log('entered the saveRowBatch callback to save to server with a rowEntity. That row is: ' + $scope.gridOptions.getRowIdentity(rowEntity));

            var deferred = $q.defer();
            $scope.gridApi.rowEdit.setSavePromise($scope.gridApi.grid, rowEntity, deferred.promise);
           // my row has a composite key on the database
            if(rowEntity.id && rowEntity.secid) {
                deferred.resolve(rowEntity);
                $log.log('finished mocking server response. success');
            } else {
                deferred.reject('This row does not have a proper id/secid. Please check data and try again');
                $log.log('failed mocking server response.');
            }
            $log.log('finished calling update');
        };

        // register row and cell edit event handlers
        $scope.gridOptions.onRegisterApi = function(gridApi) {
            $scope.gridApi = gridApi;

            gridApi.selection.on.rowSelectionChanged($scope, function(row) {
      //removed from this snippet
            });

            gridApi.edit.on.afterCellEdit( $scope, function( rowEntity, colDef ) {
                var dirtyRows = $scope.gridApi.rowEdit.getDirtyRows($scope.gridApi.grid);
                $log.log('onAfterCellEdit event triggered for row: '
                    + $scope.gridOptions.getRowIdentity(rowEntity));
                angular.forEach(dirtyRows, function(gridRow, index){
                    var key = $scope.gridOptions.getRowIdentity(gridRow.entity);
                    // if this is marked as a new row, if it's not already in our map of newRows
                    // and if the composite key is not blank, then add the row to the map of newRows
                    if("_newRow" in gridRow.entity && !(key in $scope.newRowsToBeSaved)
                        && (gridRow.entity.identifier !== "" && gridRow.entity.pattern !== "")) {
                        this[key] = gridRow;
                    }
                }, $scope.newRowsToBeSaved);

                $scope.dirtyRows = $scope.gridApi.rowEdit.getDirtyRows($scope.gridApi.grid);
            });

            gridApi.rowEdit.on.saveRow($scope, $scope.saveRowBatch);
        };

pmariduena avatar Nov 24 '14 18:11 pmariduena

Plunker seems a bit broken right now, so I can't play with it in the way I'd like, but the error message that you're getting should provide a pretty good clue:

  A promise was not returned when saveRow event was raised, either nobody is listening to event, or event handler did not return a promise 

When saveRow is called you have to call $scope.gridApi.rowEdit.setSavePromise. If you're getting that error then it suggests that you didn't call it, or didn't call it properly.

PaulL1 avatar Nov 24 '14 20:11 PaulL1

@PaulL1 That's the thing, I am calling it in my designated saveRow callback "saveRowBatch":

 $scope.saveRowBatch = function(rowEntity) {
        $log.log('entered the saveRowBatch callback to save to server with a rowEntity. That row is: ' + $scope.gridOptions.getRowIdentity(rowEntity));

        var deferred = $q.defer();
        $scope.gridApi.rowEdit.setSavePromise($scope.gridApi.grid, rowEntity, deferred.promise);
       // my row has a composite key on the database
        if(rowEntity.id && rowEntity.secid) {
            deferred.resolve(rowEntity);
            $log.log('finished mocking server response. success');

// omitted for brevity };

As you can see, I am calling setSavePromise with a Deferred object from $q.defer(), and resolving that deferred later. My "saveRowBatch" method is automatically called by the framework when I call "flushDirtyRows", once for each row I add.

So..the saveRow event is being raised (as expected) for each new row. We clearly see the event handler "saveRowBatch" return a promise (or rather, it's setting a save promise). I'm not sure who is listening to the event. But I think I've coded everything right on my end.

Maybe there is just something about my use case (calling flushDirtyRows directly).

From what I understand of flushDirtyRows(), it's supposed to mark all the rows as clean if each row has its deferred.promise resolved. That's what I think I'm doing above.

pmariduena avatar Nov 24 '14 21:11 pmariduena

Perhaps the problem is that you're resolving the promise before the callback has a chance to operate? Perhaps resolve it in a $timeout? But I think there's more to it than that, and at the moment the plunker entirely refuses to run when I click edit in plunker from the 205 tutorial, so I can't look at it properly.

PaulL1 avatar Nov 24 '14 21:11 PaulL1

@PaulL1 I was suspecting the same thing about the wrapping it in an "interval" function (not timeout). So far, adding a 100ms interval didn't help.

OK, please feel free to look at it when plunkr is up and running.

pmariduena avatar Nov 24 '14 21:11 pmariduena

It works in this plunker, and as you can see, writes out a console log for each row that is saved with different ids.

I suspect it's something in your code, but cannot really tell you what that is without a plunker of your code. http://plnkr.co/edit/SwztnW1mpIlg1oDuqWjI?p=preview

PaulL1 avatar Nov 24 '14 21:11 PaulL1

@PaulL1 Try adding new rows (as you helped me with in a previous bug). When I just modify existing rows (as you are here), it works fine for me as well.

Also, I could just send you a plunkr, and I will do that soon (working on it now).

pmariduena avatar Nov 24 '14 21:11 pmariduena

Try this plunker then - which has an addrow, and is still saving both rows successfully. http://plnkr.co/edit/SwztnW1mpIlg1oDuqWjI?p=preview

PaulL1 avatar Nov 24 '14 22:11 PaulL1

I made a plukr similar to yours and I see the culprit is the way I set up the rowIdentity for the rows, and the fact that the components of my row identity (say, the 'id' and the 'name') are things that still need to be filled in by the user after creating the row (at least in my use case):

http://plnkr.co/edit/2A7jsaCZvBRu8iV615F1

If you try this one, you'll see the behavior I am seeing. Only the last added row is saved. In my grid, my unique identifier has to be two of the columns (both of which are filled in after creating a new blank row). Although I wouldn't mind keeping around a column for unique ID purpose on the Angular JS side, one that is ultimately tossed out before saving to the server (like I currently do with the _newRows flag).

Let me know what you think about my theory here.

pmariduena avatar Nov 24 '14 23:11 pmariduena

Yeah, that was what I suggested in a previous issue on this matter - you need to sequence generate something unique on each row, or the grid thinks they're all the same row.

PaulL1 avatar Nov 24 '14 23:11 PaulL1

@PaulL1 yes I do remember that advice. But I thought that adding the incrementing integer on the end of it would fix it. I guess it also doesn't work when parts of the RowIdentity are in mid-change as well.

I can try just the index.

pmariduena avatar Nov 25 '14 03:11 pmariduena

@PaulL1 I tried just the index,, and that works...so does NOT including a rowIdentity method at all.

I have one last issue, my existing rows are not being marked as dirty after edit....I need to begin editing another cell for the row to mark dirty (rather than just single clicking another cell, as in your example).

I will start another plunkr for that but this one can close....thanks so much.

pmariduena avatar Nov 25 '14 15:11 pmariduena