JQgrid is not loading data when i redirect from one page to another in asp.net mvc4 - asp.net-mvc-4

i have an issue with my jqgrid in asp.net mvc4. i am creating user form, in this i will be adding data to user details, and when i click submit, it will be added to the database, and based on its result it will redirect to the respective page.
If adding is success, then it will be redirected to userlist page, where i have my JQgrid,the problem is, i can see the grid, but no data is there in the grid. What would be my issue.
My controller code to add a new user looks like this:
public ActionResult CreateNewUser(Tbl_Users tbl_users)
{
int userId = 1;
tbl_users.CreatedBy = userId;
tbl_users.CreatedOn = DateTime.Now;
tbl_users.ModifiedBy = null;
tbl_users.ModifiedOn = null;
if (ModelState.IsValid)
{
db.Tbl_Users.Add(tbl_users);
db.SaveChanges();
return RedirectToAction("**ListUsers**", "**Admin**");
}
ViewBag.UserCity = new SelectList(db.Tbl_Mst_City, "CityId", "CityName", tbl_users.UserCity);
ViewBag.UserDesignation = new SelectList(db.Tbl_Mst_Designation, "DesignationID", "Designation", tbl_users.UserDesignation);
ViewBag.RoleId = new SelectList(db.Tbl_Roles, "RoleID", "Role", tbl_users.RoleId);
ViewBag.CreatedBy = new SelectList(db.Tbl_Users, "UserID", "UserName", tbl_users.CreatedBy);
return View(tbl_users);
}
And My controller action to load my grid is
public ActionResult ListUsers()
{
return View();
}
public JsonResult GetUSerDetails(string sidx = "UserID", string sord = "asc", int page = 1, int rows = 5)
{
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
int totalRecords = db.Tbl_Users.Count();
int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
var userdata = db.Tbl_Users.OrderBy(sidx + " " + sord).Skip(pageIndex * pageSize).Take(pageSize)
.Select(u =>
new
{
u.UserID,
u.UserName,
u.UserEmail,
u.UserMobile,
u.UserCity,
u.UserDesignation,
u.RoleId,
u.CreatedBy,
u.CreatedOn
}).ToList();
var jsonData = new
{
total = totalPages,
page,
records = totalRecords,
rows = (
from u in userdata.AsEnumerable()
select new
{
i = u.UserID,
cell = new string[] { u.UserID.ToString(), u.UserName, u.UserEmail, u.UserMobile, u.UserCity.ToString(), u.UserDesignation.ToString(), u.RoleId.ToString(), u.CreatedBy.ToString(), u.CreatedOn.ToString() }
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
My View Page For the List User and JQgrid is looks like this:
#model FSLIWeb.Models.Tbl_Tasks
#{
ViewBag.Title = "ListUsers";
Layout = "~/Views/Shared/AdminDashboardLayout.cshtml";
}
#Html.ActionLink(" User List", "Index")
<h2>Index</h2>
<table id="jQGridDemo" width:"1024px">
</table>
<div id="jQGridDemoPager" style="width:100%">
</div>
<script type="text/javascript">
jQuery("#jQGridDemo").jqGrid({
url: 'Admin/GetUserDetails',
datatype: "json",
colNames: ['UserID','UserName','UserEmail','Contact Num','City','UserDesignation','RoleId','CreatedBy','CreatedOn'],
colModel: [
{ name: 'UserID', index: 'UserID', width: 75, align: 'center', sortable: true, editable: false, key: true, editrules: { required: true} },
{ name: 'UserName', index: 'UserName', width: 120, align: 'center', sortable: true, editable: true, edittype: 'text', editrules: { required: true} },
{ name: 'UserEmail', index: 'UserEmail', width: 100, align: 'center', sortable: true, editable: true, edittype: 'text', editrules: { required: true} },
{ name: 'UserMobile', index: 'UserMobile', width: 100, align: 'center', sortable: true, editable: true, edittype: 'text', editrules: { required: true} },
{ name: 'City', index: 'City', width: 100, align: 'center', sortable: true, editable: true, edittype: 'text', editrules: { required: true} },
{ name: 'UserDesignation', index: 'UserDesignation', width: 85, align: 'center', sortable: true, editable: true, edittype: 'text', editrules: { required: true} },
{ name: 'RoleId', index: 'RoleId', width: 70, align: 'center', sortable: true, editable: true, edittype: 'text', editrules: { required: true} },
{ name: 'CreatedBy', index: 'CreatedBy', width: 70, align: 'center', sortable: true, editable: true, edittype: 'text', editrules: { required: true} },
{ name: 'CreatedOn', index: 'CreatedOn', width: 70, align: 'center', sortable: true, editable: true, edittype: 'text', editrules: { required: true} }
],
mtype: 'GET',
loadonce: true,
rowList: [5, 10, 20, 30],
pager: '#jQGridDemoPager',
sortname: 'UserID',
viewrecords: true,
sortorder: 'desc',
width:"100%",
caption: "List Of Users",
//editurl: "//EditUser/"
});
jQuery("#jQGridDemo").jqGrid('navGrid', '#jQGridDemoPager',
{ edit: true, add: true, del: true, search: true },
{ url: "/Admin/EditUser/", closeAfterEdit: true, beforeShowForm: function (formid) { $("#UserID", formid).hide(); } },
{ url: "/Admin/AddNewUser/", closeAfterAdd: true, beforeShowForm: function (formid) { $("#UserID", formid).hide(); } },
{ url: "/Admin/DeleteUser/" }, {});
$("#search").filterGrid("#grid", {
gridModel: false,
filterModel: [{
label: 'Search',
name: 'search',
stype: 'text'
}]
});
</script>
Your Valuable Suggestion will help me to get solved this problem.
Thanks in Advance

The data URL in the jqGrid definition should be like this:
jQuery("#jQGridDemo").jqGrid({
url: '/Admin/GetUserDetails',
...
});

Related

ExtJS 3.4 GridPanel with etitable columns

I try to implement in ExtJs 3.4 a gridpanel with editable columns.
I tried to adapt this example from ExtJS but I cant get it work.
The stored values in the database are shown and as well the add button is working.
But if I click in one cell (for example column name) nothing happens, but I would expect, that the cell is 'opened' so that I can enter a new value.
Any suggestions?
CODE SNIPPET
var fm = Ext.form;
var editGrid = new Ext.grid.GridPanel({
id: 'editTable',
title: 'Edit table SAP_SYSTEM',
header: true,
renderTo: 'contentDivSystem',
height: 350,
style: 'margin-bottom: 50px',
columns: [{
hidden: true,
header: 'id',
dataIndex: 'id',
editable: false
}, {
header: 'name',
dataIndex: 'name',
editable: true,
sortable: true,
flex: 10,
editor: new fm.TextField({
xtype: 'textfield',
allowBlank: false
})
//,
//field : {
//xtype : 'textfield',
//allowBlank : false,
//}
}, {
header: 'applicationserver',
dataIndex: 'as_host',
editable: true,
flex: 10,
sortable: true,
field: {
xtype: 'textfield',
allowBlank: false
}
}, {
header: 'systemnumber',
dataIndex: 'system_number',
editable: true,
flex: 10,
sortable: true,
field: {
xtype: 'textfield',
allowBlank: false
}
}, {
header: 'client',
dataIndex: 'client',
editable: true,
sortable: true,
flex: 10,
field: {
xtype: 'textfield',
allowBlank: false
}
}, {
header: 'language',
flex: 10,
dataIndex: 'language',
editable: true,
field: {
xtype: 'textfield',
allowBlank: false
}
}, {
header: 'saprouterstring',
dataIndex: 'sap_router_string',
editable: true,
flex: 10,
field: {
xtype: 'textfield',
allowBlank: false
}
}, {
header: 'poolcapacity',
dataIndex: 'pool_capacity',
editable: true,
flex: 10,
field: {
xtype: 'textfield',
allowBlank: false
}
}, {
header: 'pool size',
dataIndex: 'pool_size',
editable: true,
flex: 10,
field: {
xtype: 'textfield',
allowBlank: false
}
}, {
xtype: 'actioncolumn',
width: 20,
align: 'center',
items: [{
icon: '../images/icons/silk/delete.png',
tooltip: 'Delete Row',
handler: function(grid, rowIndex,
colIndex) {
var rec = grid.store
.getAt(rowIndex);
if (rec.data.id !== null &&
rec.data.id !== '') {
deleteIds.push(rec.data.id);
}
grid.store.removeAt(rowIndex);
Ext.defer(layoutfunction, 10, customobject);
}
}]
}],
selType: 'cellmodel',
//plugins : [editor],
/* plugins : [ Ext.create(
'Ext.grid.plugin.CellEditing', {
clicksToEdit : 1
}) ], */
store: myStore,
stateful: false,
border: true,
enableColumnHide: false,
enableColumnMove: false,
//loadMask : true,
//stripeRows : true,
autoScroll: true,
tbar: [{
xtype: 'button',
icon: '../images//icons/silk/add.png',
dock: 'bottom',
listeners: {
click: function() {
var grid = Ext.getCmp('editTable');
var myNewRecord = new MyRecord({
id: '',
as_host: '',
system_number: '',
client: '',
language: '',
sap_router_string: '',
pool_capacity: '',
pool_size: '',
sap_id: ''
});
grid.store.add(myNewRecord);
Ext.defer(layoutfunction, 10, customobject);
}
},
afterrender: function(cmp) {
Ext.defer(layoutfunction, 100, customobject);
}
}, {
xtype: 'button',
icon: '../images//icons/silk/disk.png',
listeners: {
click: function() {
var grid = Ext.getCmp('editTable');
save(grid.store.data.items);
}
}
}],
dockedItems: [{
xtype: 'pagingtoolbar',
store: myStore, // same store GridPanel is using
dock: 'bottom',
displayInfo: true
}],
listeners: {
beforeChange: function(pagingToolbar, params) {
deleteIds = [];
updateIds = [];
pagingToolbar.store.baseParams = {
eventPath: 'FrontEndCRUDHandler',
eventMethod: 'getSapSystemData',
jsonInput: Ext.encode({
tableName: 'SAP_SYSTEM',
start: 0,
limit: rowLimit
})
}
},
afterlayout: function() {
Ext.defer(layoutfunction, 10, customobject);
},
afterrender: function(cmp) {
Ext.defer(layoutfunction, 100, customobject);
}
}
});
You must use Ext.grid.EditorGridPanel ;-)

Jqgrid filtering not working for complete word and data

Filtering of jqgrid client side. The Problems iam facing are:
Filtering is working only in two columns(Project Ref and Project name in the below code) and only or some part of the word.
Filtering is not working for the data which is coming another table. I am using two datatables for retrieving of data. Works only for the direct table doesnt work for referenced table data.
Can I have theesearch without Loadonce true.Because it is not allowing to reload
I have tried with the following below code let me know where iam doing wrong
In view:
$(document).ready(function () {
$("a.button").button();
var url = '#Url.Action("ListAllProjects")' + '?s_partId=' + '#ViewBag.PartId';
var colNames = ['<input type="checkbox" onclick="CheckAll(this.checked,\'chkOF_\',event);" name="checkall">',
'Status',
'Project Ref',
'Project Name',
'Customer',
'CreatedBy',
'Creation Date',
'Last Modified',
'LastModifiedDate',
'Edit'];
var colModel = [
{ name: 'ProjectId', index: 'ProjectId', align: 'left', formatter: checkFormatter, width: 20, search: true },
{ name: 'ProjectStatusId', index: 'ProjectStatusId', edittype: 'image', align: 'left', width: 70, formatter: imageFormatter, search: true },
{ name: 'ProjectReference', index: 'ProjectReference', align: 'left', width: 100, formatter: 'showlink', formatoptions: { "baseLinkUrl": "/Ordernew/Home" }, search: true },
{ name: 'ProjectName', index: 'ProjectName', align: 'left', width: 150, formatter: 'showlink', formatoptions: { "baseLinkUrl": "/Ordernew/Home" }, search: true },
{ name: 'CustomerName', index: 'CustomerName', align: 'left', width: 150, search: true },
{ name: 'CreatedBy', index: 'CreatedBy', align: 'left', width: 150, search: true },
{ name: 'CreationDate', index: 'CreationDate', align: 'left', width: 100, formatter: 'date', formatoptions: { srcformat: 'ISO8601Long', newformat: 'd-M-y h:m A' }, search: true },
{ name: 'LastModifiedBy', index: 'LastModifiedBy', align: 'left', width: 100, search: true },
{ name: 'LastModifiedDate', index: 'LastModifiedDate', align: 'left', width: 100, formatter: 'date', formatoptions: { srcformat: 'ISO8601Long', newformat: 'd-M-y h:m A' }, search: true },
{ name: 'StatusId', index: 'ProjectStatusId', formatter: myCustomFormatter, align: 'left', width: 70, search: true },
];
var sortname = 'ProjectStatusId';
var sortorder = 'desc';
SetGrid('#jqgprojectnew', '', url, colNames, colModel, sortname, sortorder, -1,'#count',true);
$("#jqgprojectnew").jqGrid('filterToolbar',
{
stringResult: true,
searchOnEnter: false,
defaultSearch: "cn"
});
});
And setting the grid like this which is common for all the grids. But i need search only for the above grid:
function SetGrid(v_gridCtrl,v_pagingCtrl, v_url, v_colNames, v_colModel, v_sortname, v_sortorder, v_Pagesize,Count,Loadonce) {
if (v_Pagesize == undefined)
v_Pagesize = 100;
$(v_gridCtrl).jqGrid({
//url from wich data should be requested
autowidth: true,
url: v_url,
//type of data
datatype: 'json',
//url access method type
mtype: 'POST',
//columns names
colNames: v_colNames,
//columns model
colModel: v_colModel,
//pager for grid
pager: $(v_pagingCtrl),
//enable dynamic scrolling
//scroll: true,
//enable npage request parameter
prmNames: { npage: 'npage' },
//number of rows per page
rowNum: v_Pagesize,
rowList: [10, 30, 60, 90, 100, 150, -1],
loadComplete: function () {
$("option[value=-1]").text('All');
$(Count).html($(v_gridCtrl).getGridParam("reccount"));
},
loadonce:Loadonce,
//initial sorting column
sortname: v_sortname,
//initial sorting direction
sortorder: v_sortorder,
//we want to display total records count
viewrecords: true,
//grid height
height: 400,//'100%',
//width: '100%',
scrollOffset: 0,
shrinkToFit: true,
});
}
Code for Adding record :
public bool AddUpdateOrderField(ProjectViewModelNew obj)
{
var rec = new Project
{
ProjectID = Guid.NewGuid(),
ProjectDetail = obj.ProjectDetail,
CustomerId =obj.Id,
ProjectName = obj.ProjectName,
CreatedBy = new UserManager().Userid(),
CreationDate = DateTime.Now,
LastModifiedBy = new UserManager().Userid(),
ProjectRef = obj.ProjectRef,
ProjectStatusId = obj.ProjectStatusId,
LastModifiedDate = DateTime.Now,
OwnerID = new Guid("BEBB9E61-1F06-4762-80D8-5E4D554EAEB5")
};
_context.Projects.AddObject(rec);
_context.SaveChanges();
return true;
}
If you are using local search, you should set loadonce =true and it doesn't matter, from how many tables your data is fetched to the jqgrid. If you want to make loadonce=false, then you should post search criteria to server and perform a database search.
And try removing stringResult: true, to solve your first issue
To make the search case insensitive, add this to jqgrid properties:
ie ;
$(v_gridCtrl).jqGrid({
//url from wich data should be requested
autowidth: true,
.....
ignoreCase:true,
...}
And to reload the grid, try the following code:
$( v_gridCtrl ).trigger( 'reloadGrid', [{ page: 1}] );

How to refresh jqgrid using the response data returned from the edit

I am using the inlineNav edit options for Adding and Editing rows. The data is being updated to the database correctly, but I can't find a way to refresh the grid after a successful save without posting back to the server.
All of the Questions & Answers that I find recommend doing
$.('grid').trigger('reloadGrid');
But that seems unnecessary if the response from the server already contains the required data. It is primarily an issue when adding a new record and the ID value is displayed as jqg1.
I am using ASP.NET MVC4, with jqGrid 4.4.4.
Here is my view
$(document).ready(function () {
var emptyMsgDiv = $('<div>No school codes to display.</div>');
var grid = $('#tblSchools');
grid.jqGrid({
datatype: 'json',
viewrecords: true,
url: '#Url.Action("SchoolsGridData")',
editurl: '#Url.Action("EditSchoolsGridData")',
colNames: ['School ID', 'Name', 'SACE Number', 'School Code', 'LEA Code', 'DFEE Code', 'Active'],
colModel: [
{ name: 'SchoolId', index: 'SchoolId', width: 80, key: true },
{ name: 'Name', index: 'Name', width: 190, editable: true },
{ name: 'SaceSchoolNumber', index: 'SaceSchoolNumber', width: 105, editable: true, sortable: false },
{ name: 'Code', index: 'Code', width: 105, editable: true, sortable: false },
{ name: 'LeaCode', index: 'LeaCode', width: 80, editable: true, sortable: false },
{ name: 'DfeeCode', index: 'DfeeCode', width: 80, editable: true, sortable: false },
{ name: 'Active', index: 'Active', width: 80, editable: true, sortable: false }
],
shrinkToFit: true,
height: "100%",
caption: 'School list',
rowNum: 10,
rowList: [10, 15, 20],
emptyrecords: 'No school codes to display.',
pager: '#schoolsPager',
loadComplete: function () {
var count = grid.getGridParam();
var ts = grid[0];
if (ts.p.reccount === 0) {
grid.hide();
emptyMsgDiv.show();
} else {
grid.show();
emptyMsgDiv.hide();
}
}
}).trigger('reloadGrid', [{ page: 1 }]);
emptyMsgDiv.insertAfter(grid.parent());
grid.jqGrid('navGrid', "#schoolsPager", { edit: false, add: false, del: true });
grid.jqGrid('inlineNav', '#schoolsPager', {
addParams: {
position: "last",
addRowParams: {
"keys": true,
"aftersavefunc": function (rowid, response) {
alert('row: ' + rowid + ', response: ' + $.param(response));
}
}
},
editParams: {
"aftersavefunc": function (rowid, response) {
alert('row: '+rowid+', response: '+response);
}
}
});
});
</script>
<h3>Maintain Schools</h3>
<table id="tblSchools"></table>
<div id="schoolsPager" class="gridPager"></div>
and my Controller
public JsonResult EditSchoolsGridData(string oper, string SchoolId, string Name, string SaceSchoolNumber, string Code, string LeaCode, string DfeeCode, string Active)
{
[Update Logic]
return SchoolsGridData(string.Empty, "asc", 1, 10);
}
[HttpGet]
public JsonResult SchoolsGridData(string sidx, string sord, int? page, int? rows)
{
[Get data logic]
}
I can see the response json being displayed in the aftersavefunc, but can't find a way to bind it to the grid.
Is what I'm trying to do even possible?
You can use the addRowData method which will set the data to grid with our reloading the grid
jQuery("#tblSchools").jqGrid('addRowData', response.SchoolId, response, "first");
See the jqgrid methods wiki for more details

Finding the row id in a gridpanel

How do I find the row index in a gridpanel that has comboboxes in on of the columns and is used to update the store/database through and ajax proxy? I'm using Ext.grid.plugin.CellEditing. Here's my code. Thanks for looking at it!
Ext.Loader.setConfig({
enabled: true
});
Ext.Loader.setPath('Ext.ux', '/extjs4/examples/ux');
Ext.require([
'Ext.layout.container.Fit',
'Ext.grid.*',
'Ext.data.*',
'Ext.util.*',
'Ext.panel.*',
'Ext.selection.CellModel',
'Ext.state.*',
'Ext.form.*',
'Ext.ux.CheckColumn'
]);
Ext.define('Ext.app.HirePlanGrid', {
extend: 'Ext.panel.Panel',
alias: 'widget.hirePlangrid'
,hireplanstoreId: 'hireplanstore'
,hiremonthstoreId: 'hiremonthstore'
,renderMonth : function (value, p, record) {
var fkStore = Ext.getStore(this.up('hirePlangrid').hiremonthstoreId);
var rec = fkStore.findRecord("MONTH_ID", value);
//return rec.get("ABBREVIATED_MONTH");
}
,initComponent: function() {
this.editing = Ext.create('Ext.grid.plugin.CellEditing', {
clicksToEdit: 2
});
var objMonthStore = Ext.getStore(this.hiremonthstoreId);
objMonthStore.load();
var objStore = Ext.getStore(this.hireplanstoreId);
objStore.setProxy( {
type: 'ajax',
url: 'hireplan.cfc?method=getEmployees'
});
objStore.load();
var onDeleteClick = function(field, value, options) {
// var objPanel = this.down('gridpanel');
var selection = Ext.getCmp('grid').getSelectionModel().getSelection();
alert(selection);
// var selection = getView().getSelectionModel().getSelection()[r];
if (value) {
alert(value);
objStore.remove(value);
objStore.sync();
}
};
var onUpdateClick = function(field, value, options) {
alert('field= ' + field + ' value= '+ value+ 'options= '+ options);
objStore.update(objStore.getAt(value));
onSync();
};
Ext.apply(this, {
layout: 'fit',
width: 800,
//height: 1500,
items: [{
xtype: 'grid',
id : 'gridgrid',
//height: 300,
store: objStore,
selModel: { selType: 'cellmodel' },
selType : 'rowmodel',
plugins: [this.editing],
// plugins: [cellEditing],
columnLines: true,
viewConfig: {stripeRows: true},
//loadMask: true,
disableSelection: true,
listeners: {
selectionchange: function(selModel, selected) {
var selection = Ext.getCmp('gridgrid').getSelectionModel().getSelection();
}
},
columns: [
{ header: 'rowid', hidden: true, dataIndex: 'ROWID'},
{
header: 'Indicator',
id: 'chkcolumn',
xtype: 'checkcolumn',
dataIndex: 'CHK_COL',
editor: {
xtype: 'checkbox',
cls: 'x-grid-checkheader-editor'
},
listeners : checkchange : function(column, recordIndex, checked)
{
alert('checked rindex= ' + recordIndex);
onDeleteClick(column, recordIndex, checked);
//or send a request
}
}
},
{
id: 'employeeid',
header: 'employeeid',
width: 80,
hidden: false,
sortable: true,
dataIndex: 'EMPLOYEEID',
flex: 1
},
{
id: 'NATIONALIDNUMBER',
header: 'NATIONALIDNUMBER',
width: 80,
sortable: true,
dataIndex: 'NATIONALIDNUMBER',
flex: 1
},
{
id: 'MARITALSTATUS',
header: 'MARITALSTATUS',
width: 80,
sortable: true,
dataIndex: 'MARITALSTATUS',
flex: 1
},
{
id: 'PotentialforInsourcingKV',
header: 'Potential for Insourcing',
width: 30,
sortable: true,
dataIndex: 'POTENTIAL_FOR_INSOURCING',
flex: 1,
editor: {
id: 'thiscombo',
xtype: 'combobox',
typeAhead: true,
triggerAction: 'all',
selectOnTab: true,
store: [
['1', 'Yes'],
['0', 'No']
],
lazyRender: true,
listClass: 'x-combo-list-small',
listeners: { 'select' : function(r){
var selval = Ext.getCmp("thiscombo").getValue();
//var recval = Ext.getCmp("grid").getValue();
//var selection = getView().getSelectionModel().getSelection()[r]
alert(selval + ' ' + rowIdx);
// onUpdateClick(editor, rowIdx, value );
}
},
}
},
{
id: 'ABBREVIATED_MONTH',
header: 'ABBREVIATED_MONTH',
width: 80,
sortable: true,
dataIndex: 'ABBREVIATED_MONTH',
flex: 1,
renderer: this.renderMonth,
field: {
xtype: 'combobox',
store: Ext.getStore(this.hiremonthstoreId),
typeAhead: true,
lazyRender: true,
queryMode: 'local',
displayField: 'ABBREVIATED_MONTH',
valueField: 'MONTH_ID',
listClass: 'x-combo-list-small'
}
},
{
id: 'SALARIEDFLAG',
header: 'SALARIEDFLAG',
width: 80,
sortable: true,
dataIndex: 'SALARIEDFLAG',
flex: 1
}],
features: [{
ftype: 'rowbody'
}]
}]
});
this.callParent(arguments);
//this.getSelectionModel().on('selectionchange', this.onSelectChange, this);
}, //initComponent
getSelectedRowIndex : function(){
var r, s;
r = this.getView().getSelectionModel().getSelection();
s = this.getStore();
return s.indexOf(r[0]);
},
onSelectChange: function(selModel, selections){
this.down('#delete').setDisabled(selections.length === 0);
},
onSync: function() {
objStore.sync();
},
viewConfig: {},
});
I read in another post that what I needed to do was add a listener to this.cellediting and use the 'beforeedit' event to find the row index, and then set to variables:
var rIdx = '';
var cIdx = '';
this.cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
clicksToEdit: 1,
listeners: {
'beforeedit': function(e){
var me = this;
var allowed = !!me.isEditAllowed;
if (!me.isEditAllowed)
Ext.Msg.confirm('confirm', 'Are you sure you want edit?', function(btn){
if (btn !== 'yes')
return;
me.isEditAllowed = true;
me.startEditByPosition({
row: e.rowIdx,
column: e.colIdx
});
});
rIdx = e.rowIdx;
cIdx = e.colIdx;
alert('rIdx= ' + rIdx + ' cIdx = ' + cIdx);
return allowed;
},
'edit': function(e){
this.isEditAllowed = true;
}
}
});

extjs4 ajax api store update

I'm trying to update my store and then database after using cellediting and a combobox in a gridpanel to update a record. The update operation.action in the ajax proxy is firing correctly, it just that the store and the grid aren't syncronizing, and the post tab in firebug says my json looks like this: 'data []'. How do I get the store record to create the json and update the record? Thanks for looking at this in advance...
Ext.Loader.setConfig({
enabled: true
});
Ext.Loader.setPath('Ext.ux', '/extjs4/examples/ux');
Ext.require([
'Ext.layout.container.Fit',
'Ext.grid.*',
'Ext.data.*',
'Ext.util.*',
'Ext.panel.*',
'Ext.selection.CellModel',
'Ext.state.*',
'Ext.form.*',
'Ext.ux.CheckColumn']);
Ext.define('Ext.app.HirePlanGrid', {
extend: 'Ext.panel.Panel',
alias: 'widget.hirePlangrid',
hireplanstoreId: 'hireplanstore',
hiremonthstoreId: 'hiremonthstore'
,
renderMonth: function (value, p, record) {
var fkStore = Ext.getStore(this.up('hirePlangrid').hiremonthstoreId);
var rec = fkStore.findRecord("MONTH_ID", value);
//return rec.get("ABBREVIATED_MONTH");
}
,
initComponent: function () {
var rIdx = '';
var cIdx = '';
this.editing = Ext.create('Ext.grid.plugin.CellEditing', {
clicksToEdit: 1,
listeners: {
'beforeedit': function (e) {
var me = this;
var allowed = !! me.isEditAllowed;
if (!me.isEditAllowed) Ext.Msg.confirm('confirm', 'Are you sure?', function (btn) {
if (btn !== 'yes') return;
me.isEditAllowed = true;
me.startEditByPosition({
row: e.rowIdx,
column: e.colIdx
});
});
rIdx = e.rowIdx;
cIdx = e.colIdx;
// alert('rIdx= ' + rIdx + ' cIdx = ' + cIdx);
return allowed;
},
'edit': function (e) {
this.isEditAllowed = true;
}
}
});
var objMonthStore = Ext.getStore(this.hiremonthstoreId);
objMonthStore.load();
var objStore = Ext.getStore(this.hireplanstoreId);
objStore.setProxy({
type: 'ajax',
url: 'hireplan.cfc?method=getEmployees'
});
objStore.load();
var onDeleteClick = function (field, value, options) {
// var objPanel = this.down('gridpanel');
var selection = Ext.getCmp('grid').getSelectionModel().getSelection();
// alert(selection);
//var selection = getView().getSelectionModel().getSelection()[r];
if (value) {
//alert(value);
objStore.remove(value);
objStore.sync();
}
};
var onUpdateClick = function (field, value, options) {
alert('field= ' + field + ' value= ' + value + 'options= ' + options);
objStore.update(this.hireplanstoreId, value, 'update', options);
onSync();
};
var onSync = function () {
objStore.sync();
};
Ext.apply(this, {
layout: 'fit',
width: 800,
//height: 1500,
items: [{
xtype: 'grid',
id: 'gridgrid',
//height: 300,
store: objStore,
selModel: {
selType: 'cellmodel'
},
selType: 'rowmodel',
plugins: [this.editing],
// plugins: [cellEditing],
columnLines: true,
viewConfig: {
stripeRows: true
},
//loadMask: true,
disableSelection: true,
columns: [{
header: 'rowid',
hidden: true,
dataIndex: 'ROWID'
}, {
header: 'Indicator',
id: 'chkcolumn',
xtype: 'checkcolumn',
dataIndex: 'CHK_COL',
editor: {
xtype: 'checkbox',
cls: 'x-grid-checkheader-editor'
},
listeners: {
checkchange: function (column, recordIndex, checked) {
alert('checked rindex= ' + recordIndex);
onDeleteClick(column, recordIndex, checked);
//or send a request
}
}
}, {
id: 'employeeid',
header: 'employeeid',
width: 80,
hidden: false,
sortable: true,
dataIndex: 'EMPLOYEEID',
flex: 1
}, {
id: 'NATIONALIDNUMBER',
header: 'NATIONALIDNUMBER',
width: 80,
sortable: true,
dataIndex: 'NATIONALIDNUMBER',
flex: 1
}, {
id: 'MARITALSTATUS',
header: 'MARITALSTATUS',
width: 80,
sortable: true,
dataIndex: 'MARITALSTATUS',
flex: 1
}, {
id: 'PotentialforInsourcingKV',
header: 'Potential for Insourcing',
width: 30,
sortable: true,
dataIndex: 'POTENTIAL_FOR_INSOURCING',
flex: 1,
editor: {
id: 'thiscombo',
xtype: 'combobox',
typeAhead: true,
triggerAction: 'all',
selectOnTab: true,
store: [
['1', 'Yes'],
['0', 'No']
],
lazyRender: true,
listClass: 'x-combo-list-small',
listeners: {
scope: this,
'select': function () {
var selval = Ext.getCmp('thiscombo').getValue();
var row = rIdx;
//alert(selval + ' ' + rIdx);
onUpdateClick('thiscombo', rIdx, selval);
}
}
}
}, {
id: 'ABBREVIATED_MONTH',
header: 'ABBREVIATED_MONTH',
width: 80,
sortable: true,
dataIndex: 'ABBREVIATED_MONTH',
flex: 1,
renderer: this.renderMonth,
field: {
xtype: 'combobox',
store: Ext.getStore(this.hiremonthstoreId),
typeAhead: true,
lazyRender: true,
queryMode: 'local',
displayField: 'ABBREVIATED_MONTH',
valueField: 'MONTH_ID',
listClass: 'x-combo-list-small'
}
}, {
id: 'SALARIEDFLAG',
header: 'SALARIEDFLAG',
width: 80,
sortable: true,
dataIndex: 'SALARIEDFLAG',
flex: 1
}],
features: [{
ftype: 'rowbody'
}]
}]
});
this.callParent(arguments);
}, //initComponent
onSelectChange: function (selModel, selections) {
this.down('#delete').setDisabled(selections.length === 0);
},
viewConfig: {},
});
// JavaScript Document
// JavaScript Document
hireplanstore = Ext.create("Ext.data.Store", {
model: 'HiringPlan',
//autoLoad: true,
//autoSync: true,
buffered: true,
storeId: 'hireplanstore',
remoteFilter: true
,
proxy: {
type: 'ajax',
simpleSortMode: true,
api: {
read: 'hireplan.cfc?method=GetEmployees',
update: 'hireplan.cfc?method=upEmployees',
destroy: 'hireplan.cfc?method=delEmployees'
},
reader: {
type: 'json',
messageProperty: 'message',
successProperty: 'success',
root: 'data'
},
writer: {
type: 'json',
writeAllFields: false,
root: 'data'
},
listeners: {
exception: function (proxy, response, operation) {
Ext.MessageBox.show({
title: 'ERROR from store',
msg: operation.getError(),
icon: Ext.MessageBox.ERROR,
buttons: Ext.Msg.OK
});
}
}
}
});
//hireplanstore.pageSize = 10000;
Ext.define('HiringPlan', {
extend: 'Ext.data.Model',
fields: [{
name: 'ROWID',
type: 'string'
}, {
name: 'EMPLOYEEID',
type: 'string'
}, {
name: 'NATIONALIDNUMBER',
type: 'string'
}, {
name: 'MARITALSTATUS',
type: 'string'
}, {
name: 'GENDER',
type: 'string'
}, {
name: 'POTENTIAL_FOR_INSOURCING',
type: 'integer'
}, {
name: 'ABBREVIATED_MONTH',
type: 'string'
}, {
name: 'SALARIEDFLAG',
type: 'string'
}, {
name: 'CHK_COL',
type: 'bool'
}]
});
In order to update correctly your ajax or rest call have to return an array containing the updated records, even if it's a single record, you have to return it inside an array, a sample json response (for the rest proxy) should be like this:
[{'id': 1, 'name': 'test', 'foo': 'bar'}]