Select a row by the value of one cell in jqxGrid - javascript

I've got a little question about the use of jqxGrid from jqWidgets.
I'm trying to select a row of my table dynamically from another page. I explain myself:
My first page contains a list of users. I want that when I choose an user on this list, it opens a new page with, by exemple, the ID of my user returned in GET through PHP. And then, I want to generate a new grid, with less information, but with the user already selected.
I've found how to select a row by her index $('#grid').jqxGrid('selectrow', 10); but it's not working, because if one table is sorted or filtered, the index is changed...
So, is there any way to do this ?
Here's the code wich is called when selecting a row on first table:
$('#search_right').bind('rowselect', function(event){
var iSocID = $('#search_right').jqxGrid('getcellvalue', event.args.rowindex, 'id');
$("#soci_right").load('activites/soc.search.php?a=form&id='+iSocID);
$('#content').jqxTabs('select', 3);
});
And here's the generation code of my second list:
var url = 'activites/soc.search.php';
var source = {
datatype: "json",
datafields: [
{ name: 'name', type: 'string'},
{ name: 'id', type: 'int'},
],
id: 'id',
url: url,
root: 'data'
};
dataSource = new $.jqx.dataAdapter(source);
$("#soci_table").jqxGrid({
source: dataSource,
theme: jqxGlobalTheme,
columnsresize: true,
sortable: true,
filterable: true,
showfilterrow: true,
columns: [
{ text: 'Name', dataField: 'name'},
{ text: 'ID', dataField: 'id', hidden:true},
]
});

After contacting the support of jqWidgets (who couldn't help me......) I've made a little snippet that does the tricks... But I think jqWidget should add this as a default functionnality of jqxGrid !
I paste you my code here, hope it'll help some of you !
$('#search_right').bind('rowselect', function(event){
var iSocID = $('#search_right').jqxGrid('getcellvalue', event.args.rowindex, 'id');
// Create filter
var filtergroup = new $.jqx.filter();
var filtervalue = iSocID;
var filtercondition = 'EQUAL';
var filter1 = filtergroup.createfilter('stringfilter', filtervalue, filtercondition);
var filter_or_operator = 1;
filtergroup.addfilter(filter_or_operator, filter1);
$("#soci_table").jqxGrid('addfilter', 'id', filtergroup);
// Apply filter
$("#soci_table").jqxGrid('applyfilters');
// Select row
$('#soci_table').jqxGrid('selectrow', 0);
// Remove filter
$("#soci_table").jqxGrid('clearfilters');
});

Related

Combobox Render with optional params

I am solving a requirement which can be simplified as following. I am fairly new to Ext.js and I need help in achieving the below.
I have 4 tables as follows.
So, I have 3000 companies and 9000 users mapped across various companies. I need to map moderators for each company in a grid.
I have an add button, which adds a row in the grid.
I achieved displaying the companies in the first column of a grid. Easy. So user can pick one.
I achieved displaying users belonging to that company in the second column of the grid. FYI, User can multi select moderators here.
Problem:
At this point, when I add a new row, pick a new company, the companyusers store gets refreshed, so, the values selected in 1st row are not valid values anymore and the first row's user column is displaying empty text (or) only the id's
My models are as follows
Ext.define('Mine.CompanyModel', {
extend: 'Ext.data.Model',
fields: ['Id', {name: 'Name', type:'string'}]});
Ext.define('Mine.UsersModel', {
extend: 'Ext.data.Model',
fields: ['Id', {name: 'Name', type:'string'}]});
Ext.define('Mine.CompanyUsersModel', {
extend: 'Ext.data.Model',
fields: ['company_user_id', 'UserName']}); //<companyuser Id>
Ext.define('Mine.CompanyModeratorModel', {
extend: 'Ext.data.Model',
fields: ['Id', 'CompanyUserId']});
My stores are
Ext.define('Mine.CompanyStore', {
extend: 'Ext.data.Store',
model: 'Mine.CompanyModel',
autoLoad: true,
proxy: new Ext.data.HttpProxy({
url: '/somecontroller/someaction',
reader: {
type: 'json',
root: 'Data'
}
})
});
Ext.define('Mine.UsersStore', {
extend: 'Ext.data.Store',
model: 'Mine.UsersModel',
autoLoad: true,
proxy: new Ext.data.HttpProxy({
url: '/somecontroller/someaction',
reader: {
type: 'json',
root: 'Data'
}
}),
});
Ext.define('Mine.CompanyUserStore', {
extend: 'Ext.data.Store',
model: 'Mine.CompanyUserModel',
autoLoad: false,
proxy: new Ext.data.HttpProxy({
url: '/somecontroller/someaction',
reader: {
type: 'json',
root: 'Data'
}
}),
//will add extra params here
});
Ext.define('Mine.CompanyModeratorStore', {
extend: 'Ext.data.Store',
model: 'Mine.CompanyModeratorModel',
autoLoad: false,
proxy: new Ext.data.HttpProxy({
url: '/somecontroller/someaction',
reader: {
type: 'json',
root: 'Data'
}
}),
});
My grid columns are
{
text: 'Company', width: '10%', dataIndex: 'id',
renderer: companyRenderer(combo_company), editor: combo_company
},
{
text: 'Users', width: '16%', dataIndex: 'company_user_id',
renderer: companyUsersRenderer(companyUsersCbo), editor: companyUsersCbo
}
My editor is
var companyUsersCbo = Ext.create('Ext.form.ComboBox', {
xtype: 'combo',
id: 'company_users',
name: 'company_users',
valueField: 'Id',
displayField: 'name',
allowBlank: false,
store: 'Mine.CompanyUsersStore',
multiSelect: false,
editable: true,
queryMode: 'local',
pickerAlign: 'bl',
listConfig: {
getInnerTpl: function (display) {
return '<div class="x-combo-list-item"><img src="' + Ext.BLANK_IMAGE_URL + '" class="chkCombo-default-icon chkCombo" /> {' + display + '} </div>';
}
}
listeners: {
expand: function () {
var mainGrid = Ext.getCmp('mygrid');
var selmodel = mainGrid.getSelectionModel();
var record = selmodel.getSelection();
if (record[0].get('id') != null) {
this.getStore().getProxy().setExtraParam('company_id', record[0].get('id')); // am storing the company id in a model
this.getStore().load();
}
}
}
});
My renderer is
var companyUsersRenderer = function (combo) {
return function (resources) {
var result = [];
resources = resources || [];
for (var idx = 0, len = resources.length; idx < len; idx++) {
var value = combo.getStore().find(combo.valueField, resources[idx]);
if (value != -1) {
var rec = combo.getStore().getAt(value);
result.push(rec.get(combo.displayField));
}
}
return result.join(', ');
}
}
What am I missing? What should I do so that the values (names) displayed in the combo box remain independent of the next rows.
What have I tried:: I have added a separate hidden column and set it to the names, added to the record. It worked fine, but its not the correct way. Also, when I double click the cell for editing, it shows the numbers (id's and not text) but after I expand, it shows the text.
naga Sandeep,
try to send params with your URL to get filtered records.
like,
url:'someThing/abc/1435'+'id='+record.id;
filter your store accordingly.
Problem is when your grid is rendered, your columns are rendered and your render function uses last state of the combo's store.
I would add a display field to CompanyUsersModel then fill it when a company is selected. Also I would abandon renderer function.

jqGrid Inline edit: Append custom element next to dropdown

I have the following grid which contains data from a local array (which I save with my own custom call):
var datagrid = [
{name:"Id",description:"description",entityid:"12",amount:"100"},
{name:"Id2",description:"description",entityid:"17",amount:"200"}
];
$grid = $("#grid1").jqGrid({
datatype: "local",
data: datagrid,
height: "auto",
autowidth: true,
shrinkToFit: false,
colNames:['Name','Description', 'Entity', 'Amount', ''],
colModel:[
{index: 'name', name: 'name', editable: true, edittype: 'text'},
{index: 'description', name: 'description', editable: true, edittype: 'text'},
{index: 'entityid', name: 'entityid', editable: true, edittype: 'select', formatter: 'select', edittype: 'select', editoptions:
{
dataUrl: 'url/to/drop/down/data',
buildSelect: function(data)
{
return buildSelectFromJson(data, 'oid', 'oname');
}
}
},
{index: 'amount', name: 'amount', editable: true, edittype: 'text'},
{name:'act', index:'act', sortable:false, width: "140px"}
],
onSelectRow: function(rowid){
rowSelected('grid1', rowid);
},
rowNum: 500,
editurl: "clientArray",
caption: "Details",
ajaxSelectOptions: {contentType: "application/json", dataType: 'json'}
});
$grid.jqGrid('hideCol',['act']);
Next to the "entityid" drop down I want to add a button to show a popup to enter a new entity. I want the new entity to be loaded in the drop-down after the popup closes.
Previously I used editoptions: {value: getValueFunction} but I read some advice in stack overflow which advised against it and anyway I could not load the new entity in the drop-down after the popup closed. But I was able to add the button this way:
function rowSelected(gridid, rowid){
var $grid = $("#" + gridid);
var rowData = $grid.jqGrid('getRowData', rowid);
$grid.jqGrid('showCol',["act"]);
var oneditfunction = function(){
var button = '<input id="newFieldRange" type="button" value="+"></input>';
$grid.find("select").parent().append(button);
$("#newEntity").on('click', function () {
newEntity(gridid, rowid);
});
};
$grid.jqGrid('editRow', rowid, {oneditfunc: oneditfunction});
}
Using the same code for rowSelected function and the code I showed above for the grid, the button is not added. The drop-down is filled with data successfully.
I have the following questions:
1) How can I add a custom button to "entity" cell? Is this not advised? The columns and data I show are not the real data for simplicity reasons. Due to some restrictions, it is not possible to add another column next to the drop-down (we use 'act' column for "Save" and "Cancel" buttons). I would like to add the button in the same cell as the drop-down. Unless there are alternative solutions.
2) How can I force the drop-down to reload after I close the "New entity" popup? I couldn't find anything in the jqGrid wiki.
EDIT: I was able to add the button using onsuccessfunc of jQGrid's editRow. But I am forced to use "select" jqgrid selector without specifying an id, because the and elements do not have any ids. I might need to add another dropdown which would cause issues. Am I missing something?
Thanks in advance for any responses.

Dojo DataGrid (DGrid) Adding checkbox column

I am using Dojo Dgrid however i am trying to add a checkbox column however i am not sure of the approach.
Most of the tutorials i have been looking at follow a different code structure and i am unable to create the check box column. I would like to create a checkbox column to select rows
Code (Here is also a Fiddle of my code)
require([
.......................
"dojo/domReady!"
], function(parser, declare, Grid, ColumnSet, Selection, selector,Keyboard, DijitRegistry){
parser.parse();
var data = [
{ first: "Tom", last: "Evans" },
{ first: "Sherry", last: "Young"},
{ first: "Bob", last: "William"}
];
var columns = [
[[
{editor({name: "CheckBox", field: "bool"}, "checkbox")},
{ field: "first", label: "First" },
{ field: "last", label: "Last" }]]
];
var CustomGrid = declare([Grid, ColumnSet, Selection, Keyboard, DijitRegistry]);
var grid = new CustomGrid ({
columnSets: columns ,
"class":"grid"
}, "grid");
grid.renderArray(data);
});
If you want to have a column with checkboxes for the purpose of selecting rows, you should set your sights on the selector column plugin rather than editor. selector is specifically designed to render checkboxes (or radio buttons) in each cell that ties in to the Selection mixin when checked.
See the documentation in the wiki, and the selector test page.
you can also test this solution
first you must add this Modules in require([]) section
"dgrid/extensions/ColumnResizer",
"esri/request", "dgrid/OnDemandGrid", "dgrid/Selection", "dojo/store/Memory", "dgrid/selector",
then define this array to hold your columns
var columnsPol = [];
then add check box type column to array and any other type column to array
columnsPol.push(
selector({ label: selector({}), selectorType: "checkbox" })
);
columnsPol.push({
label: "",
field: {any name},
formatter: {a function for formatting value of cell},
width: "auto",
});
.
.
.
then define your Grid and set properties
var gridPol = new (declare([Grid, ColumnResizer, Selection]))({
store: {your data},
columns: columnsPol,
minRowsPerPage: 40,
maxRowsPerPage: 40,
keepScrollPosition: true,
selectionMode: 'none',
allowSelectAll: true,
loadingMessage: "Loading data...",
noDataMessage: "No results found."
}, {Id for grid});
gridPol.refresh();
and then you can get selected and deselected rows
gridPol.on("dgrid-select", function (event) {
var selectedRows = event.rows;
});
and deselect
gridPol.on.on("dgrid-deselect",function (event){
var deselectedRows = event.rows;
});

jqgrid auto sorting the data on grouped column, how can this be turned off?

I have a jqgrid with grouping, however the data coming back from the server is already grouped, I simply want to apply the jqgrid grouping look to the data. I've included a jsfiddle since a picture speaks 1000 words. THE DATA IS INCLUDED IN THE FIDDLE...
Link to fiddle : http://jsfiddle.net/Rab815/p8Zsk/
$('table').jqGrid({
data: data,
datatype: "local",
rowNum:100,
gridview: true,
deepempty: true,
hoverrows: false,
headertitles: true,
height:'600px',
viewrecords:true,
hoverrows: true,
sortable: true,
altRows: true,
colModel: [
{ label: "Group Name", name:'groupName', field:"groupName", sortable:false},
{ label: 'Name', field: 'name', name:'name' },
{
label: 'Date Modified', field: 'lastGenerated', name:'lastGenerated'
}
],
grouping:true,
groupingView:
{
groupField: ['groupName'],
groupColumnShow: [true],
groupCollapse: true,
},
shrinkToFit: false
});
However I need it displayed in this order
Now, if you put the data in an editor so each block appears on one line, the data is already coming back grouped from the DB in the order I want it to appear. but the grid is sorting the groupName data field in 'asc' order and far as I can tell it can't be turned off.
The Grouping Column would eventually be set to groupColumnShow: [false]
ANSWER from Olegs FIDDLE...
Included a
groupOrder
in the data coming from the server rather than doing the mapping.
Altered ColModel for GroupName as follows
{
label: "Group Name", field: "groupName",
sorttype: function (cellValue, obj) {
return obj.groupOrder;
//return groupOrder[obj.groupId];
}
Now everything appears in the correct order. This solution allows the sort, which defaults to "asc" in jqgrid to order the grouped data by a different value other than the grouped data itself.
Thanks! This had me stumped for quite a while!
The problem exist because you use datatype: "local" with the data loaded from the server.
To solve your problem you can define sorttype property as function in the column "groupName" by which you sort. The function should return the value which can be used instead of the column value. For example you can extend the items of the data with new field groupOrder for example and use
sorttype: function (cellValue, obj) {
return groupOrder[obj.groupId];
}
The field should be filled on the server.
Alternatively you can fill the map between groupId in your current data model and the index to the group order. For example the code
var groupOrder = {}, i, l = data.length, groupId, groupIndex = 1;
for (i = 0; i < l; i++) {
groupId = data[i].groupId;
if (groupOrder[groupId] === undefined) {
groupOrder[groupId] = groupIndex++;
}
}
fills groupOrder in the same order in which you have the groups (you can use data[i].groupName instead of data[i].groupId in the same way). Having such groupOrder you can use
sorttype: function (cellValue, obj) {
return groupOrder[obj.groupId];
}
The demo http://jsfiddle.net/p8Zsk/38/ use the approach and it displays the groups in correct order.

Ext-JS: How to disable cell editing for individual cells in a grid?

I am now building a web application with Ext-JS 4.0.2, and I am using a editable grid to control the data to be shown for a table on the same page.
To make the grid editable, I followed the API documentation and used the following:
selType: 'cellmodel',
plugins: [
Ext.create('Ext.grid.plugin.CellEditing', {
clicksToEdit: 2
})
]
However, for this grid, there are several cells that are not supposed to be changed.
I could simply let the event handler change the data back to the right state once it is changed in the grid, but this seems to be hacky, hard to maintain, and unreadable. Is there any better way to do this? I read the API but cannot find any useful attributes.
UPDATE
As for this particular app, just disable the first row would work. But I am also interested in choose several grid and make them not editable (imagine a Sudoku game with a grid).
As I've understand from comments you want to make first row not editable. There is ugly but quick solution. Assign to your plugin beforeedit handler. And when event is being fired check what row is being edited. If first - return false:
plugins: [
Ext.create('Ext.grid.plugin.CellEditing', {
clicksToEdit: 2,
listeners: {
beforeedit: function(e, editor){
if (e.rowIdx == 0)
return false;
}
}
})
]
Check out docs for beforeedit.
UPDATE
Docs say that beforeedit has such set of params:
beforeedit( Ext.grid.plugin.Editing editor, Object e, Object options )
But there is mistake. The correct sequance is:
beforeedit( Object e, Ext.grid.plugin.Editing editor, Object options )
I've updated example due to this fact.
You can specify ColumnModel to declare editable and not editable columns:
var cm = new Ext.grid.ColumnModel({
columns: [{
dataIndex: 'id',
header: 'id',
hidden: true
},{
dataIndex: '1',
header: '1',
editor: new Ext.form.TextField({})
},{
dataIndex: '2',
header: '2',
editor: new Ext.form.NumberField({})
},{
dataIndex: '3',
header: '3'
}]
});
var grid = new Ext.grid.EditorGridPanel({
store: store,
clicksToEdit: 2,
cm: cm
...
In this example column id is unvisible, columns 1 and 2 editable (with text and number editors) and column 3 is not editable.
UPDATE:
Prevent row editing:
grid.on('beforeedit', function(event) {
if (event.row == 0) {
this.store.rejectChanges();
event.cancel = true;
}
}, grid);
As Ziyao Wei mentioned the documentation for the beforeEdit event is wrong. However you need to reference the 'editor' parameter to get the row index and other values, not the first object parameter 'e'.
Updated example:
plugins: [
Ext.create('Ext.grid.plugin.CellEditing', {
clicksToEdit: 2,
listeners: {
beforeedit: function(e, editor){
if (editor.rowIdx == 0)
return false;
}
}
})
]

Categories

Resources