Can't get selected rows with Angular UI Grid - javascript

I have two grids that have rows I can select. I want to be able to get the data in the selected rows into another data object so that I can pass it to a backend service. Here is the relevant code:
angular.module('gridPanel',['ui.bootstrap','ui.grid', 'ui.grid.edit', 'ui.grid.rowEdit', 'ui.grid.cellNav', 'ui.grid.selection'])
.controller('GridPanelController', function($scope, $log, referenceDataService){
$scope.nameGrid = {
enableRowSelection: true,
enableRowHeaderSelection: false,
multiSelect: true,
onRegisterApi: function(gridApi) {
$scope.gridApiNames= gridApi;
},
columnDefs: [
{name: 'Name', field: 'name'}
{name: 'Description', field: 'description'}
],
data:[]
};
$scope.regionsGrid = {
enableRowSelection: true,
enableRowHeaderSelection: false,
multiSelect: true,
onRegisterApi: function(gridApi) {
$scope.gridApiRegions = gridApi;
},
columnDefs: [
{name: 'Region', field: 'region'}
],
data:[]
};
referenceDataService.getAllNames().then(function (data){
$scope.nameGrid.data = data;
});
referenceDataService.getRegions().then(function (data){
$scope.regionsGrid.data = data;
});
$scope.debug = function(obj) {
var dataObj = {
names: [],
regions: []
};
dataObj.regions = $scope.gridApiRegions.selection.getSelectedRows();
dataObj.names= $scope.gridApiNames.selection.getSelectedRows();
$log.log(JSON.stringify(dataObj, null, 4));
};
});
However, when I check to see what the log says in console, it shows me that dataObj.regions and dataObj.names are both blank arrays. The data shows up fine in the actual tables, and nothing goes wrong when I click on them - I can select multiple rows without issue. The problem only comes when I click on the submit button, which for now directs to $scope.debug so that I can look at the objects in console. I have other fields in the form, mostly text fields, that also display fine when I click on debug in the console log, so the only place with an issue is getting selected rows. Thanks in advance!
edit: also, when I try to log just the 'getSelectedRows' part, it returns a blank array.

Found the problem. It's because I was using the same grids elsewhere on the webpage (within a modal) to display the same information. Once I made two sets of grids, the problem was fixed. Still seems kind of inefficient to have two sets of the same grids that serve the same purpose, but I guess maybe that's just how it is or something?

Related

how to dump all setting of handsontable instance and save to server(not save data in table to server)

I want to achieveļ¼š
One user creates handsontable using client browser: to insert or delete some columns, edit column headers, fix some rows or columns by context menu for other users to fill. So I need to save handsontable structure to server.
The following code initialize a 3*3 handsontable with contextMenu: true
var
$$ = function(id) {
return document.getElementById(id);
},
container = $$("example"),
hot;
Handsontable.dom.addEvent(createtable, "click", function() {
hot = new Handsontable(container, {
rowHeaders: true,
colHeaders: true,
dropdownMenu: true,
startRows: 3,
startCols: 3,
contextMenu: true,
licenseKey: 'non-commercial-and-evaluation',
})
})
Then I set column A readonly by context menu.
Using following code get columns option. I expect the result is [{readonly: true},{},{}], but it is undefined
Handsontable.dom.addEvent(gettablesetting, "click", function() {
console.log(hot.getSettings().columns)
})
how to dump all options of handsontable instance and save to server for other users to fill.
jsfiddle code

How to eliminate the empty rows from the jTable jQuery?

I have two jTables in my web page, which loads data from a database. The first jTable fetches the data directly from the database and the second table loads its data according to the selected data in the first table.
The problem now I am facing is, in-case if there are no data to be fetched for the second table, from the particular selected row, the rows are displaying empty.
For example, I have selected a data in the table 1, but since there is no data related to the selected data, the second table is displaying empty rows.
How to hide or not to fetch if the rows were completely empty at the same time if the row has even a single entry I wanted to display that row.
I am using python in the back end to fetch the data. So, do I need to make changes in my python code or do I need to make a change in the front end jQuery or CSS.
I have tried to use the jQuery, it is not working as expected.
My first jTable code is:
$('#SelectCode').jtable({
selecting: true,
paging: true,
actions: {
listAction:// my back end connection here
},
fields: {
codes: {
title: 'Code',
},
name:{
title: 'Name',
},
},
selectionChanged: function () {
var $selectedRows = $('#SelectCode').jtable('selectedRows');
if ($selectedRows.length > 0) {
$selectedRows.each(function () {
var record = $(this).data('record');
Code = record.event_codes;
$('#System').jtable('load',{code:(SelectedCode)});
});
},
});
My second jTable code is:
$('#System').jtable({
selecting: true,
paging: true,
actions: {
listAction:// my back end connection here
},
fields: {
date:{
title:'Date',
},
Time:{
title:'Time'
},
},
});
So, can someone, please help me how can I achieve in eliminating the empty rows from the table.
Thanks,
I have achieved it by adding the following line of codes in my jTable fields:
display: function(data) {
if (data.record.date == null) {
$("#System tr").each(function() {
var cellText = $.trim($(this).text());
if (cellText.length == 0) {
$(this).hide();
}
});
}
return data.record.date;
},

How to remove sorting on ui-grid before reload another data set ui-grid

Im using ui-grid to load my data set. Here is my requirment;
step 01: I want to load dataset_01 (scope.gridOptions.data = res_01;).
step 02: I want to sort by First Name (Click by firstname column).
step 03: Click an external button and Reload ui-grid with an another data set (scope.gridOptions.data = res_02;).
Here is my result:
I dont want sort by First Name here for second dataset.
I want data without sorting. How can I do it ?
Expected result:
So I want to reload second data set without sorting (Means I want to remove first sorting before load second data set). how can I reset my ui-grid before load next data set (scope.gridOptions.data = res_01;).
How can I do it ?
Thank you. :)
You can set the sort property of your columnDefs to:
sort: {
direction: undefined,
}
and call for grid refresh using $sope.gridApi.core.refresh() after. This should re-render the whole grid and get rid of the sorting.
Visit this page: http://ui-grid.info/docs/#/api/ui.grid.core.api:PublicApi
After having instantiated your gridApi, you can just call:
$scope.gridApi.core.refresh();
Hope that helps! :)
Create your gridoption like this
example
$scope.gridOptions = {
useExternalPagination: true,
useExternalSorting: false,
enableFiltering: false,
enableSorting: true,
enableRowSelection: false,
enableSelectAll: false,
enableGridMenu: true,
enableFullRowSelection: false,
enableRowSelection: false,
enableRowHeaderSelection: false,
paginationPageSize: 10,
enablePaginationControls: false,
enableRowHashing: false,
paginationCurrentPage:1,
columnDefs: [
{ name: "FristName", displayName: "Frist Name", width: '6%', sort: { direction: undefined } },
]
};
after that you can remove the sorting where you want using below code
$scope.RemoveSorting = function ()
{
$scope.gridOptions.columnDefs.forEach(function (d) {
d.sort.direction = undefined;
})
}

Creating ng-grids dynamically

I have a problem creating ng-grids dynamically:
The next function loops through each element of $scope.dataSparqlResponses (each element is an array of data) and put the value of the iteration in $scope.dataSparqlAux. And $scope.dataSparqlAux is the variable used in the grids (data input). The problem is that in each iteration this variable ($scope.dataSparqlAux) is reassigned, so in the template I can only see the last grid with data.
**controller.js**
$scope.crearGrids = function() {
angular.forEach($scope.dataSparqlResponses, function(elem) {
$scope.dataSparqlAux = elem.data;
$scope.dataGrids.push({grid: {
data: 'dataSparqlAux',
enablePinning: false,
showFooter: true,
selectedItems: [],
i18n: 'es',
showSelectionCheckbox: true,
afterSelectionChange: function() {
console.log(this);
},
columnDefs: [{field: elem.nombre + '.value', displayName: elem.nombre, cellTemplate: templateWithTooltip}]
}});
console.log($scope.dataGrids);
});
};
**template.html**
<div data-get-width data-num-elementos="{{dataGrids.length}}" >
<div ng-repeat="dataGrid in dataGrids">
<div class="tabla_det" ng-grid="dataGrid.grid"></div>
</div>
</div>
is possible to do something like this?
$scope.dataGrids.push({grid: {
**data: 'dataSparqlResponses[cont]',**
enablePinning: false,
showFooter: true,
selectedItems: [],
i18n: 'es',
showSelectionCheckbox: true,
afterSelectionChange: function() {
console.log(this);
},
columnDefs: [{field: elem.nombre + '.value', displayName: elem.nombre, cellTemplate: templateWithTooltip}]
}});
console.log($scope.dataGrids);
How can I fix this to create grids and display information dynamically?
Regards and thanks for your time.
EDIT: here a plunker with the problem http://plnkr.co/edit/zYtuMW4TKW053YoDY0kg?p=preview
I've shared an answer on github about your issue.
Basically, data is referencing a variable, you're not storing it.
What you can do is reference a new variable on every loop, as shown in the jsbin.
Declare an index :
var index = 0;
You declare your string with the index of the sub-document :
var dirtyConcat = 'dataSparqlResponses['+index+'].data';
Don't forget to increment the index :
++index;
Then, you reference it.
data: dirtyConcat,

jQGrid celledit in JSON data shows URL Not set alert

I need to load a JSON from server and i want to enable a user to click and edit the value.
But when they edit, it should not call server. i mean i am not going to update immediately. So i dont want editurl. So i tried
'ClientArray' But still it shows Url is not set alert box. But i need
all the edited values when the user click Add Commented Items button this button will fire AddSelectedItemsToSummary() to save those in server
MVC HTML Script
<div>
<table id="persons-summary-grid"></table>
<input type="hidden" id="hdn-deptsk" value="2"/>
<button id="AddSelectedItems" onclick="AddSelectedItemsToSummary();" />
</div>
$(document).ready(function(){
showSummaryGrid(); //When the page loads it loads the persons for Dept
});
JSON Data
{"total":2,"page":1,"records":2,
"rows":[{"PersonSK":1,"Type":"Contract","Attribute":"Organization
Activity","Comment":"Good and helping og"},
{"PersonSK":2,"Type":"Permanant","Attribute":"Team Management",
"Comment":"Need to improve leadership skill"}
]}
jQGRID code
var localSummaryArray;
function showSummaryGrid(){
var summaryGrid = $("#persons-summary-grid");
// doing this because it is not firing second time using .trigger('reloadGrid')
summaryGrid.jqGrid('GridUnload');
var deptSk = $('#hdn-deptsk').val();
summaryGrid.jqGrid({
url: '/dept/GetPersonSummary',
datatype: "json",
mtype: "POST",
postData: { deptSK: deptSk },
colNames: [
'SK', 'Type', 'Field Name', 'Comments'],
colModel: [
{ name: 'PersonSK', index: 'PersonSK', hidden: true },
{ name: 'Type', index: 'Type', width: 100 },
{ name: 'Attribute', index: 'Attribute', width: 150 },
{ name: 'Comment', index: 'Comment', editable: true,
edittype: 'textarea', width: 200 }
],
cellEdit: true,
cellsubmit: 'clientArray',
editurl: 'clientArray',
rowNum: 1000,
rowList: [],
pgbuttons: false,
pgtext: null,
viewrecords: false,
emptyrecords: "No records to view",
gridview: true,
caption: 'dept person Summary',
height: '250',
jsonReader: {
repeatitems: false
},
loadComplete: function (data) {
localSummaryArray= data;
summaryGrid.setGridParam({ datatype: 'local' });
summaryGrid.setGridParam({ data: localSummaryArray});
}
});
)
Button click function
function AddSelectedItemsToSummary() {
//get all the items that has comments
//entered using cell edit and save only those.
// I need to prepare the array of items and send it to MVC controller method
// Also need to reload summary grid
}
Could any one help on this? why i am getting that URL is not set error?
EDIT:
This code is working after loadComplete changes. Before it was showing
No URL Set alert
I don't understand the problem with cell editing which you describe. Moreover you wrote "i need the edited value when the user click + icon in a row". Where is the "+" icon? Do you mean "trash.gif" icon? If you want to use cell editing, how you imagine it in case of clicking on the icon on the row? Which cell should start be editing on clicking "trash.gif" icon? You can start editing some other cell as the cell with "trash.gif" icon ising editCell method, but I don't think that it would be comfortable for the user because for the users point of view he will start editing of one cell on clicking of another cell. It seems me uncomfortable. Probably you want implement inline editing?
One clear error in your code is usage of showSummaryGrid inside of RemoveFromSummary. The function RemoveFromSummary create jqGrid and not just fill it. So one should call it only once. To refresh the body of the grid you should call $("#persons-summary-grid").trigger("refreshGrid"); instead. Instead of usage postData: { deptSK: deptSk } you should use
postData: { deptSK: function () { return $('#hdn-deptsk').val(); } }
In the case triggering of refreshGrid would be enough and it will send to the server the current value from the '#hdn-deptsk'. See the answer for more information.
UPDATED: I couldn't reproduce the problem which you described, but I prepared the demo which do what you need (if I understand your requirements correctly). The most important part of the code which you probably need you will find below
$("#AddSelectedItems").click(function () {
var savedRow = summaryGrid.jqGrid("getGridParam", "savedRow"),
$editedRows,
modifications = [];
if (savedRow && savedRow.length > 0) {
// save currently editing row if any exist
summaryGrid.jqGrid("saveCell", savedRow[0].id, savedRow[0].ic);
}
// now we find all rows where cells are edited
summaryGrid.find("tr.jqgrow:has(td.dirty-cell)").each(function () {
var id = this.id;
modifications.push({
PersonSK: id,
Comment: $(summaryGrid[0].rows[id].cells[2]).text() // 2 - column name of the column "Comment"
});
});
// here you can send modifications per ajax to the server and call
// reloadGrid inside of success callback of the ajax call
// we simulate it by usage alert
alert(JSON.stringify(modifications));
summaryGrid.jqGrid("setGridParam", {datatype: "json"}).trigger("reloadGrid");
});

Categories