jqGrid get default entry from server side - jqgrid

I'm using a jqgrid with MVC. Here is my markup:
$("#list").jqGrid({
url: '/GstRate/GstRateGridData/',
datatype: 'json',
mtype: 'POST',
colNames: ['GstRateLookupId', 'Percentage Rate', 'Start Date', 'End Date', 'CreatedByUserName', 'CreatedDateTime', ''],
colModel: [
{ name: 'GstRateLookupId', index: 'GstRateLookupId', hidden: true, key: true, editable: true, editrules: { required: false }, editoptions: { defaultValue: '0'} },
{ name: 'PercentageRate', index: 'PercentageRate', editable: true, editrules: { required: true} },
{ name: 'StartDate', index: 'StartDate', width: 400, align: 'center', formatter: 'date', editable: true, editrules: { required: true }, formatoptions: { srcformat: 'd/m/y', newformat: 'd-m-y' }, editoptions: { dataInit: function (element) { $(element).datepicker({ dateFormat: 'd-m-y' }) } } },
{ name: 'EndDate', index: 'EndDate', width: 400, align: 'center', editable: true, formatter: 'date', formatoptions: { srcformat: 'd/m/y', newformat: 'd-m-y' }, editoptions: { dataInit: function (element) { $(element).datepicker({ dateFormat: 'd-m-y' }) } } },
{ name: 'CreatedByUserName', index: 'CreatedByUserName', hidden: true, editable: true, editrules: { required: false} },
{ name: 'CreatedDateTime', index: 'CreatedDateTime', hidden: true, editable: true, editrules: { required: false} },
{ name: 'act', index: 'act', width: 55, align: 'center', sortable: false, formatter: 'actions', formatoptions: { keys: true, delbutton: false} }
],
pager: $('#pager'),
rowNum: 10,
rowList: [5, 10, 20, 50],
viewrecords: true,
imgpath: '',
caption: 'Gst Rates',
editurl: '/GstRate/SaveGstRate/'
});
$("#list").navGrid('#pager', { edit: false, add: true, del: true, search: false }, {}, {}, { url: "/../GstRate/DeleteGstRate" });
This is working fine but I want to enhance it so that when a new entry is added the startdate value is readonly and defaults to the end date value of the last entry in the database.
The only way I can think of doing this is by somehow calling a server side method to populate the start date in the pop up create new dialog box.
I was thinking of using the dataUrl value in the editoptions to do this but this dataUrl only seems to work for when populating a select list. I don't want a select list here just a readonly text box.
Does anyone know how to achieve this?

I see two different solution ways:
You use beforeShowForm callback set input field of 'StartDate' to readonly and then send request to the server manually per $.ajax. Inside of success callback of the requests you can set the data in the input field of 'StartDate' received from the server.
If you fill the grid you use userdata to save additional information in the grid. Inside of dataInit of the 'StartDate' you get the data which you need from internal userData parameter and make the initialization of the input field.

Related

Uncaught TypeError: Cannot read property 'rowactions' of undefined in jqGrid for formatter:'action'

I am using jqGrid V 4.6.0. and trying to implement grid with inline edit/delete functionality.I used formatter:'actions' for acheive this and also getting edit/delete icons in each row.But when i click on those icons i am getting following error in console :Uncaught TypeError: Cannot read property 'rowactions' of undefined and nothing happens in grid.same code and same example i've implemented before with jqGrid V4.4.4 and it worked well ,but in V4.6.0 i got this error.Please somebody help me.Thanks in advance :)
Code for reference:
jQuery("#theGrid").jqGrid({
url: '/Student/Grid',
datatype: "json",
colNames: ['Id', 'Firstname', 'Middlename', 'Lastname', 'Birthdate', 'Birthplace', 'State', 'Nationality', 'Religion', 'Ishandicaped ?', 'Actions'],
colModel: [
{ key: true, name: 'Id', sortable: true, resize: true, align: "center" },
{ key: false, name: 'FirstName', index: 'FirstName', editable: true, align: "center", editrules: { required: true } },
{ key: false, name: 'MiddleName', index: 'MiddleName', editable: true, align: "center", editrules: { required: true } },
{ key: false, name: 'LastName', index: 'LastName', editable: true, align: "center", editrules: { required: true } },
{
key: false, name: 'Birthdate', index: 'Birthdate', editable: true, align: "center", editrules: { required: true }, formatter: 'date', editoptions: {
dataInit: function (el) {
setTimeout(function () {
$(el).datepicker({
dateFormat: "dd-M-yy",
autoSize: true,
changeYear: true,
changeMonth: true,
showButtonPanel: true,
showWeek: true
});
}, 200);
}
}
},
{ key: false, name: 'Birthplace', index: 'Birthplace', editable: true, align: "center", editrules: { required: true } },
{ key: false, name: 'State', index: 'State', editable: true, align: "center", edittype: "select", editoptions: { value: "GJ:Gujarat;MH:Maharashtra;DL:Delhi;BNG:Banglore;RJ:Rajasthan" }, editrules: { required: true } },
{ key: false, name: 'Nationality', index: 'Nationality', editable: true, align: "center", editrules: { required: true } },
{ key: false, name: 'Religion', index: 'Religion', editable: true, align: "center", editrules: { required: true } },
{
key: false, name: 'IsHandicaped', index: 'IsHandicaped', editable: true, align: "center", edittype: "checkbox", editoptions: { value: "True:False" }, formatter: Demo1
},
{
key: false,
name: 'Actions',
index: 'tax',
width: 80,
align: "center",
formatter: 'actions',
formatoptions: {
delOptions: { url: '/Student/Delete' }
}
}
],
rowNum: 10,
rownumbers: true,
autowidth: true,
rowList: [5, 10, 20],
pager: '#gridPager',
viewrecords: true,
sortorder: "desc",
reloadAfterSubmit: true,
altclass: 'table table-bordered table-striped',
jsonReader: {
repeatitems: false
},
caption:'Studentdata JqGrid V4.4.4',
editurl: '/Student/Edit',
mtype: "post",
height: '100%',
hiddengrid: false,
serializeRowData: function (postData) {
debugger;
// new row id is "new_row"
postData.Id == "jqg1" ? postData.oper = "add" : postData.oper = "add";
return postData;
},
afterSubmit: function (response, postdata) {
if (response.responseText == "") {
$(this).jqGrid('setGridParam',
{ datatype: 'json' }).trigger('reloadGrid'); //Reloads the grid after Add
return [true, ''];
} else {
$(this).jqGrid('setGridParam',
{ datatype: 'json' }).trigger('reloadGrid'); //Reloads the grid after Add
return [false, response.responseText];
}
}
}
});

How to rebind JQgrid data after applying search on the existing grid data

I have a customer details where I am showing the customers bill status which is working fine,
Is it possible to rebind the grid once we loaded the data in grid for example:
when I am coming from another page how to apply search on the existing grid data and rebind it to grid.
Below is my colmodel and other properties which I am using but not working properly,
$("#BillDetails").jqGrid({
url: '../Handler.ashx,
datatype: "json",
colNames: [ 'S.No', 'Bill NO', 'Customer Name', 'Customer Type', 'Bill Date',Bill Status'],
colModel: [
{ name: 'SERIAL', sortable: false, search: true, stype: 'text', width: 40, hidden: false,
align: 'right', sorttype: 'int' },
{ name: 'BILL_NO', sortable: false, search: true, width: 80, hidden: false,
align: 'right',formatter: editLink,},
{ name: 'CUSTOMER_NAME', search: true, align: 'left', width: 150, aligh: 'left',
sortable: false },
{ name: 'CHECK_TYPE', align: 'left', width: 150, search: true, aligh: 'left',
sortable: false},
{ name: 'BILL_DATE', width: 85, sortable: false, search: true, align: 'center',
sorttype: 'date', formatter: "date", formatoptions: { newformat: 'd/m/Y' } },
{ name: 'BILL_STATUS', width: 90, align: 'left', search: true, stype: 'select',
searchoptions: { value: 'Pending:Pending;
On Hold:On Hold;Clear:Clear;Incompelete:InComplete,sortable: false } },
],
width: '980',
height: '450',
shrinkToFit: false,
sortable: true,
mtype: 'GET',
scrollbar: true,
sortname: 'BILL_NO',
sortorder: 'asc',
hidegrid: false,
loadonce: true,
ignoreCase: true,
rowNum: 50,
pager: '#Pager',
viewrecords: true,
// Search on page load from grid data
gridComplete: function () {
var searchFilter = "Clear"; // In this I will receive the the status from query string,
//for now i have provided the the hard core value to test
var gridData = $("#jQGridDemo").jqGrid('getGridParam', 'data');
console.log(gridData);
if (searchFilter != "") {
var grid = $("#BillDetails"), f;
f = { rules: [] };
f.rules.push({ field: "STATUS", op: "eq", data: searchFilter });
grid[0].p.search = true;
$("#BillDetails").setGridParam({ data: gridData, postData: { filters: f },
datatype: "local", });
}
}
});
If you want to reload jqGrid when coming from another page with search parameters you could use postData property of jqGrid.
Something like this:
$("#BillDetails").jqGrid({
url: '../Handler.ashx',
datatype: "json",
mtype: 'GET',
postData:
{
Page: 'Dashboard',
strUserID: strUserID,
}
You can populate this property with js or on server side as you need.
UPDATE
You also can use setGridParam method of jqgrid:
$("#BillDetails").jqGrid('setGridParam',
{
postData: {
Page: 'Dashboard',
strUserID: strUserID,
}
});
$("#BillDetails").trigger("reloadGrid");
But as i understand this way you also just add values to postData property.
Also you can try it this way:
$("#BillDetails").trigger('reloadGrid', [{page:1}]);
You can pass there your new params as on grid init.

How to reload a jqGrid with new query string value

I load jqgrid with drop down values using onchange event.
But when i again choose some other value in drop down i need the jqgrid to show the corresponding values.
Here s how i load the jqgrid
function getGrid() {
var mOptometrist = $('#optOptometristList').val();// Drop down value
alert(mOptometrist);
//jQuery("#list").jqGrid().setGridParam({ url: 'Schedule.ashx?mOptometristId=' + mOptometrist + '' }).trigger("reloadGrid");
jQuery("#jQGridDemo").jqGrid({
url: 'Schedule.ashx?mOptometristId=' + mOptometrist + '',
datatype: "json",
colNames: ['Id', 'Day', 'Start Time', 'End Time', 'Interval', 'Session', "Patient", 'Slots', 'Room Number'],
colModel: [
{ name: 'SlNo', index: '_id', width: 20, stype: 'text', editable: true, editoptions: { disabled: true} },
{ name: 'DayOfWeek', index: 'Day', width: 150, stype: 'text', sortable: true, editable: true, edittype: "select", formatter: 'select', editoptions: { value: getAllSelectOptions()} },
{ name: 'StartTime', index: 'StartTime', width: 150, editable: true, formatter: 'date', formatoptions: { srcformat: 'u', newformat: 'H:i:s'} },
{ name: 'EndTime', index: 'EndTime', width: 60, editable: true, formatter: 'date', formatoptions: { srcformat: 'u', newformat: 'H:i:s'} },
{ name: 'Interval', index: 'Interval', width: 80, align: "right", editable: true },
{ name: 'Session', index: 'Session', width: 40, align: "right", editable: true },
{ name: 'PatientsPerSlot', index: 'Patient', width: 80, align: "right", editable: true },
{ name: 'Slots', index: 'Slots', width: 150, sortable: false, editable: true },
{ name: 'RoomID', index: 'RoomNumber', width: 100, sortable: false, editable: true }
],
rowNum: 10,
mtype: 'GET',
loadonce: false,
rowList: [10, 20, 30],
pager: '#jQGridDemoPager',
sortname: '_id',
viewrecords: true,
sortorder: 'desc',
caption: "List Employee Details",
editurl: 'Schedule.ashx?mOptometristId= ' + mOptometrist,
loadComplete: function () {
$("#jQGridDemo").setColProp('Day', { editoptions: { value: "1:Sunday;2:Monday;3:Tuesday"} });
}
});
You can use
url: "",
postData: {
mOptometristId: function () {
return $('#optOptometristList').val();
}
}
instead of
url: 'Schedule.ashx?mOptometristId=' + mOptometrist + ''
Inside of onchange event you need just call $("#jQGridDemo").trigger("reloadGrid");. See the answer for more details.

how to set the jqgrid column width, and re-sizable, in a scrollable jqgrid?

i am using jqgrid and facing a problem with column width
here is my js code
jQuery(document).ready(function () {
var grid = jQuery("#grid");
grid.jqGrid({
url: '/Admin/GetUserForJQGrid',
datatype: 'json',
mtype: 'Post',
cellsubmit: 'remote',
cellurl: '/Admin/GridSave',
//formatCell: emptyText,
colNames: ['Id', 'Privileges', 'First Name', 'Last Name', 'User Name', 'Password', 'Password Expiry', 'Type', 'Last Modified', 'Last Modified By', 'Created By', ''],
colModel: [
{ name: 'Id', index: 'Id', key: true, hidden: true, editrules: { edithidden: true } },
{ name: 'Privileges', index: 'Privileges', width: "350", resizable: false, editable: false, align: 'center', formatter: formatLink, classes: 'not-editable-cell' },
{ name: 'FirstName', index: 'FirstName', width:350, align: "left", sorttype: 'text', resizable: true, editable: true, editrules: { required: true } },
{ name: 'LastName', index: 'LastName',width:350, align: "left", sorttype: 'text', resizable: true, editable: true, editrules: { required: true } },
{ name: 'UserName', index: 'UserName', width:300,align: "left", sorttype: 'text', resizable: true, editable: true, editrules: { required: true } },
{ name: 'Password', index: 'Password',width:400, align: "left", sorttype: 'text', resizable: true, editable: false, editrules: { required: true }, classes: 'not-editable-cell' },
{
name: 'Password_Expiry',width:250, index: 'Password_Expiry', align: "left", resizable: true, editable: true, editoptions: {
size: 20, dataInit: function (el) {
jQuery(el).datepicker({
dateFormat: 'yy-mm-dd', onSelect: function (dateText, inst) {
jQuery('input.hasDatepicker').removeClass("hasDatepicker")
return true;
}
});
}
}
},
{
name: 'Type', width: "250", index: 'Type', sorttype: 'text', align: "left", resizable: true, editable: true, editrules: { required: true }, edittype: 'select', editoptions: {
value: {
'Normal': 'Normal',
'Sales': 'Sales',
'Admin': 'Admin',
'SuperAdmin': 'SuperAdmin'
},
dataEvents: [
{
type: 'change',
fn: function (e) {
var row = jQuery(e.target).closest('tr.jqgrow');
var rowId = row.attr('id');
jQuery("#grid").saveRow(rowId, false, 'clientArray');
}
}
]
}
},
{ name: 'Modified',width:250, index: 'Modified', sorttype: 'date', align: "left", resizable: true, editable: false, classes: 'not-editable-cell' },
{ name: 'ModifiedBy', width:250, index: 'ModifiedBy', sorttype: 'text', align: "left", resizable: true, editable: false, classes: 'not-editable-cell' },
{ name: 'CreatedBy', width:250,index: 'CreatedBy', sorttype: 'text', align: "left", resizable: true, editable: false, classes: 'not-editable-cell' },
{ name: 'Delete',width:50, index: 'Delete', width: 25, resizable: false, align: 'center', classes: 'not-editable-cell' }
],
rowNum: 10,
rowList: [10, 20, 50, 100],
sortable: true,
delete: true,
pager: '#pager',
height: '100%',
width: "650",
afterSubmitCell: function (serverStatus, rowid, cellname, value, iRow, iCol) {
var response = serverStatus.responseText;
var rst = 'false';
debugger;
if (response == rst) {
debugger;
setTimeout(function () {
$("#info_dialog").css({
left: "644px", // new left position of ERROR dialog
top: "380px" // new top position of ERROR dialog
});
}, 50);
return [false, "User Name Already Exist"];
}
else {
return [true, ""];
}
},
//rowNum: 10,
//rowList: [10, 20, 50, 100],
sortable: true,
loadonce: false,
ignoreCase: true,
caption: 'Administration',
search: false,
del: true,
cellEdit: true,
hidegrid: false,
pgbuttons : false,
pginput : false,
//viewrecords: true,
gridComplete: function () {
var ids = grid.jqGrid('getDataIDs');
for (var i = 0; i < ids.length; i++) {
var isDeleted = grid.jqGrid('getCell', ids[i], 'Delete');
if (isDeleted != 'true') {
grid.jqGrid('setCell', ids[i], 'Delete', '<img src="/Images/delete.png" alt="Delete Row" />');
}
else {
grid.jqGrid('setCell', ids[i], 'Delete', ' ');
}
}
}
}
);
grid.jqGrid('navGrid', '#pager',
{ resize: false, add: false, search: false, del: false, refresh: false, edit: false, alerttext: 'Please select one user' }
).jqGrid('navButtonAdd', '#pager',
{ title: "Add New users", buttonicon: "ui-icon ui-icon-plus", onClickButton: showNewUsersModal, position: "First", caption: "" });
});
i need a scrollable grid , when use come to this page i have to show the first 7 columns only just seven in full page. i have 11 columns in my grid rest of the columns can be seen by using scroll, but first 7 should be shown when grid loads. and every column should be re-sizable. can any body help me, i will 100% mark your suggestion if it works for me ...thank you ;) . if something is not explained i am here to explain please help me
and can i save the width of column permanently when user re-size the column, so when next time grid get loads the column should have the same width which is set by the user by re-sizing.. is it possible ?
I am not sure what you want,but you can auto adjust the width with JqGrid autowidth and shrinkToFit options.
Please refer this Post jqGrid and the autowidth option. How does it work?
this will do the trick.

NO URL IS SET - error in jqGrid (Add, Delete dialog)

I've following Grid to display data, now when I want to add new record it gives the error 'NO URL IS SET'
$(document).ready(function () {
$('#PRGrid').jqGrid({
//url from wich data should be requested
url: '#Url.Action("BindData")?FillType=' + getFillType(),
//event for inline edit
onSelectRow: function (currentSelectedRow) {
if (currentSelectedRow && currentSelectedRow != $.lastSelectedRow) {
//save changes in row
$('#PRGrid').jqGrid('saveRow', $.lastSelectedRow, false);
$.lastSelectedRow = currentSelectedRow;
}
//trigger inline edit for row
},
//type of data
datatype: 'json',
//url access method type
mtype: 'POST',
//columns names
colNames: ['Code', 'Name', 'No_Rooms', 'Dept_Code', 'Total_Items'],
//columns model
colModel: [
{ name: 'Code', index: 'Code', align: 'left', width: '120px', editable: true, edittype: 'select', editoptions: { maxlength: 25, dataUrl: '#Url.Action("GetRooms")',
dataEvents: [{
type: 'change', fn: function (e) {
var ret = $.ajax({
url: '#Url.Action("selectRoom")?id=' + $(this).val(),
async: false,
success: function (ret) {
$('#Name').val(ret.Name);
$('#No_Rooms').val(ret.qty);
$('#Dept_Code').val(ret.DeptCode);
$('#Total_Items').val(ret.Total_Items);}
});}
}]
}},
{ name: 'Name', index: 'Name', align: 'left', formatter: "text", width: '185px', editable: true, editrules: { required: true }, editoptions: { readonly: 'readonly'} },
{ name: 'No_Rooms', index: 'No_Rooms', align: 'left', formatter: "text", width: '102px', integer: true, editable: true, editrules: { required: true }, editoptions: { readonly: 'readonly'} },
{ name: 'Dept_Code', index: 'Dept_Code', align: 'left', formatter: "text", width: '78px', editable: true, editrules: { required: true }, editoptions: { readonly: 'readonly'} },
{ name: 'Total_Items', index: 'Total_Items', align: 'left', formatter: "text", width: '82px', integer: true, editable: true, editrules: { required: true }, editoptions: { readonly: 'readonly'} },
],
//pager for grid
pager: $('#PRGridPager'),
//number of rows per page
rowNum: 5,
//initial sorting column
sortname: 'Code',
//initial sorting direction
sortorder: 'asc',
recreateForm:true,
//we want to display total records count
viewrecords: true,
//grid height
height: '100%'
});
$('#PRGrid').jqGrid('navGrid', '#PRGridPager',
{ add: true, del: true, edit:false, search: true },
{width: '330', url:'#Url.Action("InsertPRGridRecord")', closeAfterAdd: true },
{width: '330', url:'#Url.Action("DeleteGridRecord")'});
var dialogPosition = $(this).offset();
Problem arrise when I want to add or delete the record from the grid,
Here I've defined both the methods InsertPRGridRecord() and DeleteGridRecord(), but it gives the same error 'NO URL IS SET' at the time of submitting the data on Add Record or Delete Record dialog.
I think the problem exist because you use incorrect the parameters of navGrid. Your current code uses '#Url.Action("DeleteGridRecord")' as URL of "Add" and '#Url.Action("InsertPRGridRecord")' as URL of "Edit". The URL of "Delete" is not specified.

Resources