Length of colNames <> colModel! error in JQGRID - jqgrid

I am using data of following format in jqgrid "1201.2564.2548.25456". This throws the following error while displaying the data from JSON: Length of colNames <> colModel!
ANy idea.. is it related to format of the data?

Both parameters colNames and colModel are arrays, which have to have the same number of elements (the length). You use different length. One of possible error which I have seen before was the usage of strings "[...]" instead of arrays [...] as the value of colNames and colModel. As the result jqGrid code compared the length of the strings colNames and colModel instead of comparing the number of elements in arrays colNames and colModel. Such error could take place if you returns colNames and colModel from the server and you have used wrong JSON serialization on the server side.
Thus you should verify that the type of colNames and colModel are arrays and both arrays have the same number of elements.

It is mandatory to match the count of columns with the entries in the colModel.
Following error is prompted majorly if the columns count is not equal to number of entries inside the colModel. So colModel should match the count of ColNames.
E.g.
colNames: ['ID', 'First', 'Last', 'Email'],
colModel: [
{ name: "ID", index: "id", width: 100 },
{ name: "FirstName", index: "firstName", width: 100 },
{ name: "LastName", index: "lastName", width: 100 },
{ name: "Email", index: "email", width: 100 }
],

Related

ID values for jqGrid select lists

I am using jQrid version 3.8.1 and I have a grid that displays information about cars. The jQgrid should is set up to display one car per row and one of the columns is a multi-select list that displays which types of seats the car is configured with. A car can have multiple seat types.
When the user edits a car row, it makes an ajax query to get all of the seats types available in the system and sticks them in the multi-select list. In addition to populating the list, it needs to also select the options already chosen for that car.
The values inside the Installed Seats column are not simple strings. They have both an ID and a string value. So the ID for "Wire mesh" might be 2883 and the value for "Composite" might be 29991. They are just unique numeric values (basically the primary key from the table they are stored in).
After the multi-select list is populated with all the appropriate Seat values, I need to select the ones that the car currently has installed (in the picture above it's "Steel" and "Wire frame"). I need to do this based on the seat IDs stored for that car. However, I don't know where these value are going to come from. The grid only stores the names for the seats, not the IDs. Hopefully there is a way to make it store both.
The column model looks like this:
colModel: [
{ name: 'Year', index: 'Year', editable: true, edittype: "select", editoptions: { multiple: true } },
{ name: 'Make', index: 'Make', editable: true, edittype: "select", editoptions: { multiple: true } },
{ name: 'Body', index: 'Body', editable: true, edittype: "select", editoptions: { multiple: true } },
{ name: 'Seats', index: 'Seats', editable: true, edittype: "select", editoptions: { multiple: true }, cellattr='is-seat-list="1"' }
]
Notice that the 'Seats' model has a cell attribute called is-seat-list. I'm using this to find the select box in the row inside the 'editRow' function.
The onSelectRow handler looks like this:
onSelectRow: function (index) {
var curValues = $('#cargrid').getRowData(index);
jQuery('#cargrid').jqGrid('editRow', index, true, function(rowId) {
//when the user edits the row, query for all the seat types and fill in the list
jQuery.ajax({
url: '/getalltheseats',
complete: function (allSeats, stat) {
var list = $('#cargrid').find('tr[id="' + rowId + '"] td[is-seat-list="1"] select');
var $list = $(list);
//add the all seat types to the list, checking the ones that this car currently has selected
_.each(allSeats, function(seat) {
var selected = '';
if(curValues['Seats'].indexOf(seat.ID) !== -1) //<-- what do I do here??
selected = 'selected';
$list.append($('<option ' + selected + '></option>').attr('value', seat.ID).text(seat.Name));
});
});
});
});
},
The important line is
if(curValues['Seats'].indexOf(seat.ID) !== -1)
I have the value of the row but it only contains the seat name, not the ID. The data returned from the ajax call contains each seat name and ID but the <option> elements don't contain the ID value so I don't know which ones to select in the list.
So the question is, what's the best way to make jqGrid store both the seat names and IDs so that when I create the list dynamically, I can check the <option>s for the seats that have been chosen for that car.
Note:
For various reasons the standard dataUrl and buildSelect features of jqGrid are not going to work for me, which is why I'm building the list on the fly in this manner.
First of all you need additionally add formatter: "select" and to populate ID values in Seats column during filling of the grid. The formatter: "select" will decode the IDs and the corresponding Name value will be displayed to the user.
If you would use more recent version of jqGrid the you can use beforeProcessing callback created for the purpose. It allows to include all different ID/Name pairs in the server response for filling of the grid. It allows you to fill the information needed for the formatter: "select" directly in the main server response. You don't need to load the information before creating the grid.
If you use retro version of jqGrid (3.8.1) then I hope that you can still use the following trick. You can define userdata part of the server response defined as function. The outer elements of the server response root, page, total, records and userdata will be processed before the processing the main part with all items. It allows you to modify editoptions.value before it will be processed by formatter: "select".
For example the response from the server can looks like
{
"page": 1,
"total": 20,
"records": 400,
"userdata": {
"seats": "29991:Composite;42713:Nappa leather;6421:Steel;2883:Wire mesh"
},
"rows": [
{
"year": 2007,
"model": "Toyota/Camry",
"body": "Sedan",
"seats": "29991,6421"
},
{
"year": 2057,
"model": "BMW/Series 4",
"body": "Sedan",
"seats": "6421,2883"
}
]
}
Inside of jsonReader you can define userdata which set userdata.seats as value of editoptions. You can use setColProp method for example to do this.
In the way you will be able to implement all your requirements.

jqGrid casting data to a String before sort

I'm trying to sort a list of orders based on total money spent on the purchase. The list looks like this (extra fields omitted for clarity):
[
{products:[
{name: 'foo',price:2.53},
{name: 'bar',price:5.74}
]},
{products:[
{name: 'baz',price:6.74},
{name: 'quux', price:7.68}
]}
]
The column definition in question looks like this (with sumPricesOf taking an array similar to the above and returning the total spent):
{
name: 'products',
label: 'Total spent',
index: 'products',
formatter: function(d){return '$'+sumPricesOf(d.products)},
sorttype: 'function',
sortfunc: function(a,b){
return sumPricesOf(a.products) - sumPricesOf(b.products);
}
}
However, if I use console.log(a,b) in the sortfunc, when it gets called a and b are getting passed as strings! The arguments get passed as [object Object],[object Object].
Why can't jqGrid just give me back the data that I passed it?
Strong recomend use sorttype: float option in colModel array.

jqGrid text Sort Order

I have a jqGrid that I set up like this
gridAltMpn.jqGrid({
autowidth: true,
shrinkToFit: true,
datatype : 'local',
data : input,
height : '100',
scrollrows: true,
scrollOffset : '0',
hidegrid : false,
colNames : [ 'P', 'MPN' ],
colModel : [
{ name : 'Col1', width : 30, align:'center' },
{ name : 'Col2', width : 250, sorttype: 'integer'}
],
pager : '#altmpn_pager',
pagerpos : 'left',
scroll: 50,
gridview : true,
caption : 'A useful table title',
emptyRecordText : '<div id="no_data_msg" style="text-align:center"> No Results Found</div>',
hoverrows : true,
onSelectRow: function(id) {
var gsr = gridAltMpn.jqGrid('getGridParam', 'selrow');
if (gsr) {
var rowData = gridAltMpn.jqGrid('getRowData', gsr);
if ($("input[name='optInvInqType']:checked").val() == 'MPN') {
getInvInq("MPN", rowData.MPN);
}
}
},
loadComplete: function() {
gridAltMpn.setSelection(gridAltMpn.getDataIDs()[0], true);
}
});
The data in this grid looks like this
XX 774860A6
774860A8
774860A4
774860A3
774860A10
STARTER, PNEUM,PW4000
When the grid is first loaded that it fine but if the user wants to sort by the second column it ends up like this
774860A10
774860A3
774860A4
XX 774860A6
774860A8
STARTER, PNEUM,PW4000
The 774860A10 should go after the 774860A8 just like in an integer sort. I cannot use an integer sort because these are not integers as there is some alpha characters in there. In other words I want a text entry to sort like an integer. Do I need to use a custom sort routine and then have my Javascript to do a integer like sort? I also don't need this sorted on the first time because my server sorts it by the first column. The user might want it sorted by the second column
You should use a custom function for this type of sorting.
For this, set sort type property of jqgrid as your custom function. As stated in this link, sort type can have the following values.
sorttype:
int/integer - for sorting integer
float/number/currency - for sorting decimal numbers
date - for sorting date
text - for text sorting
function - defines a custom function for sorting. To this function we pass the value to be sorted and it should return a value too.
And the custom function can be something like this: (From this link found in the answer by Oleg for this question.)
colModel: [
{name:'Posn', index:'Posn', width:100, sorttype:
function(cell)
{
//Here you have to apply your own logic
if (cell=='GK') return '0';//returns the sort order
if (cell=='DEF') return '1';
if (cell=='MID') return '2';
if (cell=='STR') return '3';
}
},
By the way, you can set the sortname property of jqgrid to set a column for initial loadtime sorting.

jqgrid editable x number formating is inconsisent with format on grid

I've built a grid as the code bellow:
colModel: [
{ name: 'price',
label: 'price',
index: 'price',
jsonmap: 'price',
formatter: 'number',
formatoptions: {decimalSeparator:",", thousandsSeparator: ".", decimalPlaces: 2, defaultValue: '0,00'},
editable: true
}
]
The format of field is correctly on grid, for instance: 10,32, but the form created to edit the field fills one with 10.32 instead of 10,32.
Someone knows why this is going on? Do I need to use properties as edittype and editoptions (this one using formmater and formatoptions) as well? if yes, How I need set up these properties?
I've fixed the problem using the the function afterShowForm to handle the formating of field on form generated from grid.
In fact, I was expecting that jQGrid could do that automatically, i.e, using the configuration provided to column to apply on field generated, or if i could apply the configurion on JSON message, for instance:
editoptons: { formatter = "number", formatteroptions = { .... } ...
anyway, it's working now.

Sorting in Dojo 1.5 datagrid doesn't work

I have built a dojo 1.5 datagrid + dojox.data.JsonRestStore. When the grid renders I can see the "carrot" that shows that sorting has fired and is on defaulting the right column. However, the content of the column(string values - field: 'projectShortName',...see code below) are not actually sorted. Hitting the descending/ascending button doesn't change the order or the rows. They are essentially locked in. I am not sure why?
I have column sorting turned off for certain columns and on for others using the canSort(). I only have formatters for calls with columns that have the sort turned OFF. I have tried making all columns sortable or only just the one that I really wanted. No dice.
Here is the layout/grid code:
var layout = [{
field: '_item',
name: '&nbsp',
formatter: selectFormatter,
width: '25px'
},
{
field: 'projectName',
name: 'Project Name',
width: '325px'
},
{
field: 'projectShortName',
name: 'Short Name',
width: '80px'
},
{
field: 'projectAreaName',
name: 'RQM Project Area',
width: '175px'
},
{
field: '_item',
name: 'Test Guide Status',
width: '190px',
formatter: testCaseGenerationOptionFormatter
},
{
field: 'projectOwner',
name: 'Owner',
width: '140px'
},
{
field: 'projectCreationTime',
name: 'Created Date',
width: '100px'
},
{
field: 'projectLastUpdateTime',
name: 'Last Modified Date',
width: '120px'
}];
dojo.empty(dojo.byId('workspaceGridContainer'));
if (dijit.byId("projectGrid")) {
dijit.byId("projectGrid").destroyRecursive();
}
// Create a new grid:
var grid = new dojox.grid.DataGrid({
id:'projectGrid',
onHide: dojo.hitch(this, function() {
dijit.byId("projectGrid").destroyRecursive();
}),
store: jsonStore,
clientSort: true,
autoHeight: true,
//sortInfo: "-2",
selectionMode: 'single',
rowsPerPage: '100',
structure: layout
},document.createElement('div'));
dojo.byId("workspaceGridContainer").appendChild(grid.domNode);
// Call startup, in order to render the grid:
grid.startup();
//var test = grid.setSortInfo(obj);
// Prevent sorting on column 1
grid.canSort = function(col){ if((Math.abs(col) == 1) || (Math.abs(col) == 5) || (Math.abs(col) == 6) || (Math.abs(col) == 7) || (Math.abs(col) == 8)) { return false; } else { return true; } };
var index = grid.getSortIndex();
if(index!=2) {
if(grid.canSort(2)){
grid.setSortIndex(2, false);
}
}
As you can see commented out I have tried sortInfo as well. Any advice would be appreciated!
-Doug
You may be using the wrong comparison operator. The dojo documentation uses the strict equal '===' whereas you only use the equal '=='. This causes problems in js, especially when you're comparing a literal, i.e. '1' with an object: 'Math.abs(col). The official grid.canSort method should be coded as follows:
function canSort(col){ return Math.abs(col) === 2;}
Note Mozilla's description of the equal operator, and the type conversion js uses to resolve different data types:
https://developer.mozilla.org/en/JavaScript/Reference/Operators/Comparison_Operators
Equal (==) - If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers if possible; else if either operand is a string, the other operand is converted to a string if possible. If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.

Resources