How to disabled or hide editoption value to a id session specific with jqgrid? - jqgrid

I am new to using jqgrid and what I try to do is that a specific id cannot edit the record by placing the status sold
here an example of the condition that I try to apply
if(session_level == 9){
{name:'status', index:'status', width:150, formatter: editexample, editable:true, stype: 'select', edittype:'select',
editoptions: {value: {'':'','New':'New','Cancelled':'Cancelled'} }, search: true,
searchoptions:{ sopt:['eq'], value: {'': 'Select', '':'', 'New':'New','Cancelled':'Cancelled'} }
},
}else
{name:'status', index:'status', width:150, formatter: editexample, editable:true, stype: 'select', edittype:'select',
editoptions: {value: {'':'','New':'New','Sold':'Sold','Cancelled':'Cancelled'} }, search: true,
searchoptions:{ sopt:['eq'], value: {'': 'Select', '':'', 'New':'New','Sold':'Sold','Cancelled':'Cancelled'} }
},

I'm not sure that I understand correct the question, but you can simple do it like this
var my_object = {'': 'Select', '':'', 'New':'New','Cancelled':'Cancelled'};
if(session_level == 9){
my_object['Sold']= 'Sold';
}
jqGrid({
....
colModel[
...
{name:'status', index:'status', width:150, formatter: editexample, editable:true, stype: 'select', edittype:'select',
editoptions: {value: my_object }, search: true,
searchoptions : { sopt:['eq'], value: my_object } }
...
]
});
in case this is a JavaScript. In case of PHP or other server side language you should do it in appropriate way

Related

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.

jqGrid, searching dates

My data is on the server side, I have code written to do all the searching/filtering/ordering.
My jqGrid has both a filterToolbar, and a search button.
Unfortunately, when I search, the value I pick for the date, is not sent in the request. However, oddly, it DOES send it when it's the filterToolbar's selected date?!?
Why is there nothing in data here?
{"groupOp":"AND","rules":[{"field":"RunDate","op":"le","data":""}]}
Here is my code for the grid.
var loadFileInfoList = function (fileInfoList, pager) {
fileInfoList.jqGrid({
url: 'GetFiles',
datatype: 'json',
mtype: 'POST',
colNames: ['Id', 'Name', 'Interface', 'Amount', 'Type', 'Created', 'Status'],
colModel: [
{ jsonmap: 'Id', name: 'Id', formatter: 'integer', align: 'right', hidden: true },
{ jsonmap: 'Name', name: 'Name', align: 'right', hidden: true },
{ jsonmap: 'InterfaceName', name: 'InterfaceName', align: 'left', width: '100%', sorttype: 'text', frozen: true,
search: true,
searchoptions: {
sopt: ['cn']
}
},
{ jsonmap: 'Amount', name: 'Amount', formatter: 'currency', align: 'right', width: '100%', sorttype: 'number',
search: true,
searchoptions: {
sopt: ['ge', 'le']
}
},
{ jsonmap: 'Type', name: 'Type', align: 'right', width: '100%', sorttype: 'text',
search: true, stype: 'select',
searchoptions: {
value: getTypeFilterOptions(),
sopt: ['eq']
}
},
{ jsonmap: 'RunDate', name: 'RunDate', formatter: 'date', align: 'right', width: '100%', sorttype: 'date',
search: true,
datefmt: 'dd/mm/yyyy',
searchrules: {
date: true
},
searchoptions: {
sopt: ['ge', 'le'],
dataInit: function (elem) {
$(elem).datepicker({
dateFormat: 'dd/mm/yy',
changeYear: true,
changeMonth: true,
showButtonPanel: true,
onSelect: function () {
$(this).keydown();
}
});
}
}
},
{ jsonmap: 'Status', name: 'Status', align: 'right', width: '100%', sorttype: 'text', formatter: formatStatus,
search: true, stype: 'select',
searchoptions: {
value: getStatusFilterOptions(),
sopt: ['eq']
}
}
],
autoencode: true,
sortname: 'RunDate',
sortorder: 'desc',
pager: pager,
rowNum: 5,
viewrecords: true,
height: '100%',
autowidth: true,
ignoreCase: true,
jsonReader: {
repeatitems: false,
root: "rows"
},
altRows: true,
altclass: 'jqGridAltRow',
loadComplete: function () {
$("tr.jqgrow:odd").addClass('jqGridAltRow');
}
});
fileInfoList.jqGrid('navGrid', pager,
{ edit: false, add: false, del: false },
{},
{},
{},
{ closeOnEscape: true, closeAfterSearch: true, multipleSearch: true, multipleGroup: false }
);
fileInfoList.jqGrid('filterToolbar', { searchOnEnter: false, enableClear: true, stringResult: true });
};
loadFileInfoList($('#jqgFileInfoList'), '#jqgPagerFileInfoList');
I suppose that you can solve the problem by changing onSelect callback of datepicker. You can change
onSelect: function () {
$(this).keydown();
}
to
onSelect: function () {
$(this).trigger('change');
}
You can use also more complex construct which I posted in the answer or a little more simple form from here.

returns false for data value loadComplete jqGrid

EDITED JS:
$.extend($.jgrid.defaults,
{
mtype: "POST",
viewRecords: true,
rowNum: 10,
sortable: false,
shrinkToFit: true,
rowList: [10,20,50],
xmlReader: {
root: "tasks",
row: "task",
repeatitems: false
}
});
<script>
var subjects = <?php echo $Subject ?>;
var users = <?php echo $trimmed ?>;
var lastsel3;
$(document).ready(function () {
$grid = $("#assign"),
initDateEdit = function (elem) {
setTimeout(function() {
$(elem).datepicker({
dateFormat: 'yy-mm-dd',
showButtonPanel: true
});
}, 100);
},
initDateSearch = function (elem) {
setTimeout(function() {
$(elem).datepicker({
dateFormat: 'yy-mm-dd',
showButtonPanel: true
});
}, 100);
};
$grid.jqGrid({
url: 'assignedTasks.php',
colNames: ["track","Assigned To","JobID","Subject","Notes","Details","Due Date","Submit Date", "AssignUser"],
colModel: [
{
name: "track",
index:"TrackID",
key: true,
align: "center",
xmlmap:"TrackID",
hidden: true
},
{
name:"User",
index:"UserID",
align: "center",
editable: true,
xmlmap:"UserID",
edittype: 'select',
editoptions: {value: users},
editrules: {required: true},
sortable: false
},
{
name: "JobID",
index:"TaskID",
xmlmap:"TaskID",
editable: true,
align:"center",
editrules: {required: true},
sortable: false,
},
{
name: "Subject",
index:"TaskSubject",
align: "center",
xmlmap:"TaskSubject",
editable: true,
edittype: 'select',
editoptions: {value: subjects},
editrules: {required: true},
sortable: false
},
{
name:"Notes",
index:"Notes",
align: "center",
height: 20,
xmlmap:"Notes",
editable: true,
edittype: 'textarea',
sortable: false
},
{
name:"Details",
index:"Details",
align: "center",
xmlmap: "Details",
editable: false,
sortable: false
},
{
name:"DueDate",
index:"DueDate",
align: "center",
editable: true,
xmlmap:"DueDate",
editrules:{required: true},
editoptions: {dataInit: initDateEdit},
formatter: 'date',
formatoptions: {newformat: 'd-M-Y'},
datefmt: 'd-M-Y',
sortable: false
},
{
name:"Submitted",
index:"Submitted",
align: "center",
xmlmap: "Submitted",
editable: false,
sortable: false
},
{
name:"AssignUser",
index:"AssignUser",
align: "center",
xmlmap: "AssignUser",
hidden:true,
editable: false
}
],
loadComplete : function()
{
var rows = $grid.jqGrid('getDataIDs');
alert(rows);
for (ID in rows)
{
var data = $grid.getCell(ID,'Details');
alert(data);
}
},
gridview: true,
ondblClickRow: function(track){
if(track && track!==lastsel3)
{
$('#assign').jqGrid('restoreRow',lastsel3);
$('#assign').jqGrid('viewGridRow',track);
lastsel3=track;
}
else
{
$("#assign").jqGrid('viewGridRow',track);
}
},
editurl: 'addTasks.php',
pager: $('#assignNav'),
caption: "Assign Tasks"
}).navGrid('#assignNav',{edit:true,add:true,del:true},{},{},{},{multipleSearch: false, multipleGroup: false});
$(window).bind('resize', function() {
$("#assign").setGridWidth($(window).width()-"185");
$("#assign").setGridHeight($(window).height()-"310");
}).trigger('resize');
});
setInterval(
function(){
$('#assign').setGridParam({datatype: 'xml'}).trigger('reloadGrid',[{current:true}]);
},60000);
</script>
I am using this event to get the value inside the cell. When i run the code the alert returns "false" for the first couple of cells even though they have a value assigned and then returns the right value for all the corresponding ones. How do i fix this?
I tried gridComplete event and the result was the same.
XML:
<?xml version="1.0" encoding="UTF-8" ?>
<tasks>
<task>
<TaskID>job0001</TaskID>
<UserID>admin</UserID>
<AssignID></AssignID>
<AssignDate></AssignDate>
<DueDate></DueDate>
<AssignUser>1</AssignUser>
<TaskSubject></TaskSubject>
<Notes>Urgent!</Notes>
<TrackID>1</TrackID>
<Details>Not Started</Details>
<Submitted></Submitted>
<folderLink></folderLink>
</task>
<task>
<TaskID>job00004</TaskID>
<UserID>admin</UserID>
<AssignID></AssignID>
<AssignDate>2012-02-07</AssignDate>
<DueDate>2012-02-16</DueDate>
<AssignUser>1</AssignUser>
<TaskSubject></TaskSubject>
<Notes>ajsbaljb</Notes>
<TrackID>7</TrackID>
<Details>Not Started</Details>
<Submitted></Submitted>
<folderLink></folderLink>
</task>
</tasks>
EDIT 2: If I do this
loadComplete : function()
{
var data = $grid.getCol('Details');
alert(data);
},
it returns everything correctly!
loadComplete : function()
{
var data = $grid.getCol('Details', true);
},
This returns exactly what I had in the Details Cell with the rowIds. This solved where I was stuck but I would still like to know why the other function returned false.

jqGrid get default entry from server side

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.

jqgrid search toolbar not coming up using jquery.jqgrid.js

I am trying to add the search bar with jquery.jqgrid.js after trying several methods this method was the only one that did not give me an error but neither does it show my search toolbar, can someone have a look and see if I missing anything??
jQuery(document).ready(function() {
jQuery("#list").jqGrid({
url: '/Home/DynamicGridData/',
datatype: 'json',
mtype: 'POST',
colNames: ['Edit', 'AlertId', 'Policy', 'PolicyRule', 'Alert Status',
'Alert Code', 'Message', 'Category'],
colModel: [
{ name: 'Edit', edittype: 'select', formatter: 'showlink' },
{ name: 'AlertId', index: 'AlertId', sortable: true, sorttype: 'int',
autoFit: true, align: 'left', hidden: true },
{ name: 'Policy', index: 'Policy.Name', sortable: true, sorttype: 'text',
autoFit: true, searchoptions: { sopt: ['eq', 'ne', 'cn'] },
align: 'left' },
{ name: 'Policy Rule', index: 'PolicyRule', sortable: true,
sorttype: 'text', autoFit: true, sorttype: 'text',
searchoptions: { sopt: ['eq', 'ne', 'cn'] }, align: 'left' },
{ name: 'Alert Status', index: 'AlertStatus.status', sortable: true,
sorttype: 'text', searchoptions: { sopt: ['eq', 'ne', 'cn'] },
autoFit: true, align: 'left' },
{ name: 'Alert Code', index: 'Code', sortable: true, sorttype: 'text',
align: 'left', searchoptions: { sopt: ['eq', 'ne', 'cn'] },
autoFit: true },
{ name: 'Message', index: 'Message', sortable: true, sorttype: 'text',
align: 'left', searchoptions: { sopt: ['eq', 'ne', 'cn'] },
autoFit: true },
{ name: 'Category', index: 'Category.name', sortable: true,
sorttype: 'text', align: 'left', autoFit: true,
searchoptions: { sopt: ['eq', 'ne', 'cn'] }}],
pager: $("#pager"),
rowNum: 10,
rowList: [10, 60, 100],
scroll: true,
sortname: 'AlertId',
sortorder: 'asc',
viewrecords: true,
imgpath: '/scripts/themes/basic/images',
caption: 'my name',
gridComplete: function() {
var objRows = $("#list tr");
var objHeader = $("#list.jqgfirstrow td");
if (objRows.length > 1) {
var objFirstRowColumns = $(objRows[1]).children("td");
for (i = 0; i < objFirstRowColumns.length; i++) {
$(objFirstRowColumns[i]).css("width",
$(objHeader[i]).css("width"));
}
}
}
});
});
$("#list").jqGrid('navGrid','#pager',
{edit:true,add:true,del:true,search:true,refresh:true});
$("#list").jqGrid('navButtonAdd',"#pager",
{caption:"Toggle",title:"Toggle Search Toolbar",
buttonicon :'ui-icon-pin-s',
onClickButton:function() {
$("#list")[0].toggleToolbar()
} });
$("#list").jqGrid('navButtonAdd',"#pager",
{ caption: "Clear", title: "Clear Search",
buttonicon :'ui-icon-refresh',
onClickButton:function(){
$("#list")[0].clearToolbar()
} });
jQuery("#list").jqGrid('filterToolbar');
After the improving of the format of your code one can see your main error: you call navGrid, navButtonAdd and filterToolbar outside of jQuery(document).ready. If you move it inside the jQuery(document).ready you will see immediately the searching toolbar: see here.
You code has other small problems:
variable i inside gridComplete should be declared to be local and not global variable.
You should remove deprecated parameter imgpath.
You use many options of colModel parameters with default values like sortable:true, sorttype: 'text', align: 'left' and so on. It makes only the code longer, slowly and more difficult to read. I recommend you to look in the part of documentation which describes colModel parameters and remove default properties.
The sorttype property which you use will not work in case of usage datatype: 'json' without loadonce:true. So you should decide either you use server based sorting, paging and filtering/searching and you should better remove in the case sorttype properties or you should use loadonce:true, but the grid contain should be loaded at once at the first request to the server.
There are no autoFit column property.

Resources