ID values for jqGrid select lists - jqgrid

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.

Related

jqgrid reading form element value and dynamically changing select option

I like to change the Type field drop down option depending on the inputs of Year and Level fields.
I am able to trigger an event when Level is change.
But how do I get the value of the Year field?
Portion of the code are as follows
colModel:[
{name:'Year',index:'Year', width:70,sortable:false,editable:true,align:'center',editoptions:{size:15, maxlength:4}, formoptions:{ rowpos:1, label: "Year (*)"},editrules:{required:true}},
{name:'Level',index:'Level', width:70,sortable:false,editable:true,align:'center',edittype: "select", editoptions: { value: '1:1;2:2;3:3;4:4;5:5;6:6', defaultValue:'1', dataEvents : [
{
'type' : 'change',
'fn' : function ( el ) {
// get the newly selected value from the user
var levelz = $(el.target).val(), yearz ;
var row = $(el.target).closest('tr.jqgrow');
var rowid = row.attr('id');
//yearz = ??
if (parseInt(levelz)==5 || parseInt(levelz)==6)
{
if (parseInt(yearz)>2017)
{
$("#gridmain").jqGrid('setColProp','Term', {editoptions: { value: '1:Sem 1;4:Sem 2;6:EY;9:OVR', defaultValue:'Sem 1'}} );
}else{
$("#gridmain").jqGrid('setColProp','Term', {editoptions: { value: '', defaultValue:''}} );
}
}else{
$("#gridmain").jqGrid('setColProp','Term', {editoptions: { value: '1:TA1/CT1;2:TA2-before 2013;3:MY/TA2/CT2;4:TA3/CT3;5:TA4-before 2013;6:EY/TA4/CT4;9:OVR;D:CW1;E:CW2;F:CW3;G:CW4', defaultValue:'TA1'}} );
}
}
}]}, formoptions:{ rowpos:2, label: "Level (*)"},editrules:{required:true}},
{name:'Term',index:'Term', width:70, sortable:false,editable: true,align:'center',edittype: "select", editoptions: { value: '1:TA1/CT1;2:TA2-before 2013;3:MY/TA2/CT2;4:TA3/CT3;5:TA4-before 2013;6:EY/TA4/CT4;9:OVR;D:CW1;E:CW2;F:CW3;G:CW4', defaultValue:'TA1'}, editrules: { required: true }, formoptions:{ rowpos:3, label: "Type"}},
The codes are from piecing together what I read from google search...
I face 2 issues:
1) I don't know how to get the Year value
2) The drop down option list doesn't seems to change. - hmm it seems that if I close the edit form and open again, the Type field drop down option changes. What I need is to change the option on the fly - wonder how this can be done...
After much googling, managed to get the ans from Oleg's post as shown here
Also from his example, I derive the year value:
var yearz = $("#Year.FormElement", form[0]).val();

How do I programmatically select from a select2 dropdown when using the tablesorter.filterformatter widget?

I would like to be able to programmatically select something from a dropdown, as in http://select2.github.io/select2/#programmatic. But the dropdown also seems to be generated (I didn't include it anywhere in the HTML) by the filterformatter widget, which I initialized with:
$('#client_table').tablesorter({
theme: "blue",
headers: {1: {sorter: 'types'}},
widgets: ["filter", "zebra"],
widgetOptions : {
filter_formatter: {
1 : function ($cell, indx) {
return $.tablesorter.filterFormatter.select2($cell, indx, {
closeOnSelect: false,
placeholder: "Select events",
allowClear: true,
match: false, // exact match only
});
},
What element do I call select2 on in this case? What are the values/data that I should be using (the thing I would like to select, for example, is the string APP_STATE).
When select2 is applied to the table, the table cell gets a class name of select2col0 where (0 is the column zero-based index).
If you open this demo and enter the following code in the console, it'll programmically set the value:
$('.select2col0').find('input').select2('val', ['abc']);

How do I get the formatted value of one column in another column in jqgrid

How do I get the formatted value of one column in another column in jqgrid.
For eg:
{ name: 'amount', index: 'amount', sorttype: "float", formatter: processAmount, title: false },
{ name: 'netAmount', index: 'netAmount', sorttype: "float", formatter: function (cellvalue, options, rowObject)
{
// How do I get the formatted value of column "amount" here?
}
}
I know that I am posting very little of my requirement or code. But I hope this is sufficient. Please let me know if you need more information on anything.
Thanks,
Sam
Custom formatters will be called before the body of the grid will be placed on the page. So you can't access the formatted value of one column inside of custom formatter of another column. What you can still do is calling of another formatfer. For example you can call processAmount function inside of formatter of netAmount column.

Sorting a Column by Default (on load) Using Dojo Dgrid

When loading a dgrid from a dojo store, is there a way to specify a column to be sorted by default.
Say I have 2 columns, Name and Email, I want the name column sorted by default when the grid is first loaded. What I want is the equivalent of the user clicking on the 'Name' header (complete with the sort arrow indicating the sort direction).
Thanks,
John
You can do something like this :
var mygrid = new OnDemandGrid({
store : someStore,
queryOptions: {
sort: [{ attribute: "name" }]
}
// rest of your grid properties
}, "someNode");
dgrid 1.1.0 - set initial/default sort order
var TrackableRest = declare([Rest, SimpleQuery, Trackable]);
var store = new TrackableRest({target: apiUrl, useRangeHeaders: true, idProperty: 'id'});
var grid = new (declare([OnDemandGrid, Selection, Editor]))({
collection: store,
sort: [{"property":"name", "descending": false}],
className: "dgrid-autoheight",
columns: {
id: {
label: core.id
},
category_text: {
label: asset.category
},
name: {
label: asset.model,
},

Is it possible to search locally in jqGrid with treeGrid installed

I am using jqGrid with treeGrid. I have added a filterToolbar. I would like to search locally instead of having a server call. The treegrid docs say that, "When we initialize the grid and the data is read, the datatype is automatically set to local." (This is regards to TreeGrid)
So, is it possible to implement local search with treeGrid. I tried the below configuration, but it is resulting in server calls.
My Configuration is
var grid = $("#grid").jqGrid({
treeGrid: true,
treeGridModel: 'adjacency',
ExpandColumn: 'businessAreaName',
ExpandColClick : true,
url:'agileProgramme/records.do',
datatype: 'json',
mtype: 'GET',
colNames:['Id'
, 'Business Area'
, 'Investment'
, 'Org'
, 'Goal'
],
colModel:[
/*00*/ {name:'agileProgrammeId',index:'agileProgrammeId', width:0, editable:false,hidden:true},
/*01*/ {name:'businessAreaName',index:'businessAreaName', width:160, editable:false},
/*02*/ {name:'programmeName',index:'programmeName', width:150, editable:false, classes:'link'},
/*03*/ {name:'org',index:'org', width:50, editable:false, classes:'orgHierarchy', sortable : false},
/*04*/ {name:'goal',index:'goal', width:70, editable:false}
],
treeReader : {
level_field: "level",
parent_id_field: "parent",
leaf_field: "leaf",
expanded_field: "expanded"
},
autowidth: true,
height: 240,
pager: '#pager',
sortname: 'id',
sortorder: "asc",
toolbar:[true,"top"],
caption:"TableGridDemo",
emptyrecords: "Empty records",
jsonReader : {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
cell: "cell",
id: "agileProgrammeId"
}
});
And to implement the search toolbar
$('#grid').jqGrid('filterToolbar', {stringResult: true,searchOnEnter : true});
Would appreciate any help or any pointer on even if it is possible?
The most problem in the TreeGrid filtering is that it's not clear what should be displayed in the TreeGrid as the result of applying the filter. The standard behavior of applying filter to the grid consist from removing all non-filtered rows. Such behavior will be wrong in case of TreeGrid. In the answer to the close question I tried to explain the problem.
What one can try to implement is some kind of highlighting of the filtered rows only (see here as an idea) or one can set some CSS class to the non-filtered rows to make there gray (like disabled). In any way one have to display parents of the filtered rows in some way. One more option will be to display the filtered TreeGrid not in the Tree form. On can display for example an additional column with the path to the filtered row and the rest row data.
UPDATED: What I mean with "to display parents of the filtered rows" is about the following. Let us we have the TreeGrid like the following
+root 123
+testchild1 32
test1 4
+child2 30
test2 7
and we filter for the first column for the text "test". In the case it would be wrong to display just the lines which has the text "test"
+testchild1 32
test1 4
test2 7
but in some scenarios if would be enough to display the above lines with the full path till the root element:
root\testchild1 32
root\testchild1\test1 4
root\testchild1\test2 7
In the case the information will be displayed in the grid instead of TreeGrid.
In other cases the searching in the leafs only can have sense. In the case one could really display the results in the TreeGrid form, but it will be not the common case.

Resources