I have a jqGrid where the formatter function for the colModel must be defined as a string
{name:'FileSize', index:'FileSize', width:90, editable: true,
formatter: 'fileSizeFormatter'}
I can't use the following where the formatter function is not a string because I build the colmodels on the server side in C#. If I could use the non string formatter Defining unformatter would be a solution as shown in
Here
{name:'FileSize', index:'FileSize', width:90, editable: true,
formatter: fileSizeFormatter}
And here is the fileSizeFormatter I needed to use fn.fmatter because my formatter is passed as a string and the code assumes it is one of the predefined one's lile "select", "currency"...etc
$.fn.fmatter.fileSizeFormatter = function (cellval, options) {
var fileUnit = "B";
if (cellval) {
var fileUnit;
var iKBFileSize;
if (cellval < 1024) {
iKBFileSize = cellval;
} else {
iKBFileSize = cellval / 1024;
fileUnit = "KB";
}
var result = iKBFileSize.toFixed(1) + fileUnit;
return result;
}
return cellval + fileUnit;
};
Sample
So the question is how can I define unformatter for a formatter which is passed as a string. When I do grid.getrowdata or edit the cell my unformatter is not being used. It is getting me the data with the file unit.
$.unformat.fileSizeFormatter = function (cellvalue, options, cell) {
return $('input', cellval).is(":checked") ? true : false;
};
You should define unformatter in a little another way:
$.fn.fmatter.fileSizeFormatter.unformat = function (cellValue, options, elem) {
return $(elem).find('input').is(":checked") ? true : false;
}
You should define unformatter of cause after defining the formatter ($.fn.fmatter.fileSizeFormatter).
Related
I have a jqGrid custom function as editrules: { custom: true, custom_func: checkforduplicates, required:true }
However, I want this function to be run only in add mode, not in edit mode. Is this possible ?
EDIT:- After answer below from Oleg, I changed code to below. However, the alert does not print. Not sure where I am going wrong.
colModel: [
{ key: true, name: 'id', editable: false, formatter: 'integer', viewable: false, hidden: true },
{
key: false,
name: 'name',
editable: true,
editrules: {
required: true,
custom: function (options) {
// options have the following properties
// cmName
// cm
// iCol
// iRow
// rowid
// mode - "editForm", "addForm", "edit", "add", "cell" and so on
// newValue - the value which need be validated
// oldValue - the old value
// some additional properties depends on the editing mode
alert("mode is " + options.mode);
if (options.mode === "add") { // "add" for inline editing
var grid = $("#grid");
var textsLength = grid.jqGrid("getRowData");
var textsLength2 = JSON.stringify(textsLength);
alert("i am here");
var myAttrib = $.map(textsLength,
function (item) { return item.name });
var count = 0;
for (var k in textsLength) {
if (textsLength.hasOwnProperty(k)) {
++count;
}
}
var text, i;
for (i = 0; i < count; i++) {
text = myAttrib[i];
if (value === text) {
return [false, " - Duplicate category name."];
}
}
return [true, ""];
}
return true;
}
}
},
Free jqGrid supports old style custom_func with the options value, name and iCol and the new style validation. To use new style validation one don't need to specify any custom_func callback, but to define custom as the calback function with one parameter:
editrules: {
required: true,
custom: function (options) {
// options have the following properties
// cmName
// cm
// iCol
// iRow
// rowid
// mode - "editForm", "addForm", "edit", "add", "cell" and so on
// newValue - the value which need be validated
// oldValue - the old value
// some additional properties depends on the editing mode
if (options.mode === "addForm") { // "add" for inline editing
// do the validation
}
return true;
}
}
In case of validation of Add form the mode property is equal to "addForm", options.iRow === -1, options.oldValue === null, options.rowid === "_empty". It's recommended to use options.mode to detect the editing (or searching mode) in free jqGrid because the values of other properties (iRow, oldValue and rowid) depends on the editing mode.
For version 4.7 I use this method. Form for adding data class for the table. After that, special actions verified by the user are performed.
{
name : "LOGIN",
index : "LOGIN", editrules: {
required:true,
custom:true,
custom_func: dublicateUser
}
...
{
closeAfterAdd : true,
width : 500,
recreateForm : true,
afterShowForm : function () {
jQuery("#TblGrid_list_users").addClass('addMode');
}
...
function dublicateUser() {
var a;
var login = jQuery('#LOGIN').val();
var checkMode = jQuery('#TblGrid_list_users').hasClass('addMode');
jQuery.ajax({
type: 'POST',
data: {login:login, mode:checkMode},
url: 'code/validate_user.php',
async: false,
success: function(data) {
if (data == 'err') {
a = 1;
}
else {
a=0;
}
}
});
if (a==1) {
return[false,"error"];
}
else {
return[true];
}
}
i have a js file and the function name called viewLineBtn.
in my server code, i have created a list of object
List<GridModelClass> addmodelResult = new List<GridModelClass>();
addmodelResult.Add(new GridModelClass { name = "AddTestApprove", label = "Approve", width = "40", hidden = false, formatter = "viewLineBtn" });
however, the viewLineBtn can not be recognize. How to solve it?
It seems that you returns colModel as JSON data return from the server. As the result you have formatter property which have the type string (like formatter: "viewLineBtn") instead of function (like formatter: viewLineBtn, where viewLineBtn defined before as a function).
To fix the problem you can change how you defined formatter function. Instead of the usage
function viewLineBtn (cellValue, options, rowObject) {
// do something here
return htmlFragmentOfCell;
}
you should use
$.extend($.fn.fmatter, {
viewLineBtn: function (cellValue, options, rowObject) {
// do something here
return htmlFragmentUsedInCell;
}
});
In the case you can use formatter: "viewLineBtn" in colModel.
I would recommend you to define always custom unformatter (unformat property) if you defines custom formatter. To do this in case of usage string value of formatter you should define unformatter in the following way:
$.extend($.fn.fmatter, {
viewLineBtn: function (cellValue, options, rowObject) {
// do something here
return htmlFragmentUsedInCell;
}
});
$.extend($.fn.fmatter.viewLineBtn, {
unformat: function (cellValue, options, elem) {
// do something here
return htmlFragmentFromDomElem;
}
});
I want to reuse the following code for custom_func:
function validLen(value,colName){
if(value.length === 8){
return [true,""];
}
else{
return [false,"fail"];
}
}
I tried giving it an additional parameter as follows:
function validLen(value,colName,length){
if(value.length === length){
return [true,""];
}
else{
return [false,"fail"];
}
}
And calling it like this:
{name:'cntrct_id', editrules:{custom: true, custom_func:validLen(8)} },
Didn't work. The previous code DOES work, but as stated, I want a reusable function. Is there a workaround for this? Am I doing it wrong?
I would recommend you to use
editoptions: { maxlength: 8}
instead of the custom validation which you use. In the case the input element will be created with the maxlength attribute directly. So the user will not able to type more as characters as specified by maxlength.
UPDATED: You can't change the interface of any callback function, but you can do share common code of different custom_func in the following way. You define your custom validation function having three parameters like
function validLen (value, colName, valueLength) {
if (value.length === valueLength) {
return [true, ""];
}
else {
return [false, "fail"];
}
}
and use it in the following way
{
name: 'cntrct_id',
editrules: {
custom: true,
custom_func: function (value, colName) {
return validLen(value, colName, 8);
}
}
If you need to use this inside of custom_func then you can change return validLen(value, colName, 8); to return validLen.call(this, value, colName, 8);.
I'm using select type inside a column , when I'm generating the xml from the grid's data , i can't get the value of the select type cell.
This is my code:
{name:'code',index:'code', width:80, sorttype:"int" , editable:true,edittype:"select",
editoptions:
{
value:"1:11 ;2:22" }
and the xml generating is with:
var dataFromGrid = grid.jqGrid ('getRowData');
var xml = xmlJsonClass.json2xml ({Row: dataFromGrid}, '\t');
I get inside the xml "11" intead of "1".
How can i get the option value?
Thank's In Advance.
I had to do this in local processing mode:
var rows = jQuery(this).getRowData();
var cols = jQuery(this).jqGrid('getGridParam', 'colModel');
for (var col in cols) {
if (cols[col].edittype == 'select') {
var VALs = cols[col].editoptions.value;
if (typeof (VALs) == "object") {
for (var row in rows) {
for (var v in VALs) {
if (rows[row][cols[col].name] == VALs[v]) {
rows[row][cols[col].name] = v;
break;
}
}
}
}
}
}
If you use datatype:"xmlstring" it will be changed to the "local" datatype after the filling of the grid. So like in case of the datatype:"local" the grid has internal data parameter which represent grid data and not the visualization of the current page of data which you receive with
var dataFromGrid = grid.jqGrid ('getRowData');
So I recommend you to use
var dataFromGrid = grid.jqGrid ('getGridParam', 'data');
to get the data from the grid.
if you only need the selected ID in the data, you can specify formatter: 'select'
...
{
name: 'unit', index: 'unit', editable: true, formatter: 'select', edittype: 'select', editrules: { required: true }, editoptions: { value: "1:11 ; 2:22" }
},
...
then retriving the grid data :
var griddata = $('#gridID').getGridParam('data');
alert(JSON.stringify(griddata));
In my jqgrid when i am clicking on add new record i have date field prepopulated with current date. Format of the date is yyyy-MMM-d (e.g. 2010-Jan-23).
Date is required field and when i click submit button it fails validation and displays error that this date is invalid, and it wants Y-m-d format.
How can i check my value with jqgrid? In other words how to make jqgrid accept the following date format when validating 2010-Jan-23?
Thanks.
Here is my JSON data:
{"rows":[
{"id":1,"cell":["2010-Mar-3","Pepto","2","False","not active"]},
{"id":2,"cell":["2009-May-6","Tylenol","5","False","not active"]},
{"id":3,"cell":["2008-May-6","Aspirin","9","True","active"]}
]}},
Here is my date column definition:
{ name: 'Date',
index: 'date',
width: '80px',
align: 'center',
sortable: false,
editable: true,
datefmt: 'Y-M-d',
editoptions: { dataInit: function(elem) { $(elem).datepicker({ dateFormat: 'yy-M-d' });},value: getDate } ,
editrules: { required: true, date:true} },
The getdate function inserts current date into field. here is the function:
function getDate(){
var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var now = new Date();
return now.getFullYear() + "-" + monthNames[now.getMonth()] + "-" + now.getDate();
}
Maybe this is because of this function? Can i insert current date from datepicker?
Amount of data sent from the server is not too big (about 10-30 rows) and this application will be used by maximum of 50 people, so there is no concerns regarding amounts of data.
Anytime when i have value as 2010-Jun-23 in the field, i get error message:Enter valid date value - Y-M-d
Verify that you defined datefmt: 'Y-M-d' in the column definition of colModel. In the list of editrules options (see http://www.trirand.com/jqgridwiki/doku.php?id=wiki:common_rules#editrules) is defined that if you use date: true as a editrules option, the validation will be done corresponds with the datefmt option.
Some more recommendations if you use date in jqGrid:
If you not yet use, think about of the usage of jQuery.datepicker (see http://jqueryui.com/demos/datepicker/#date-formats) inside of dataInit function of editoptions (like
editoptions: {
dataInit : function (elem) {
$(elem).datepicker();
}
// ...
}
in the simplest case). If you use searching for date fields, you can use dataInit with jQuery.datepicker also in searchoptions in the same way (see http://www.trirand.com/jqgridwiki/doku.php?id=wiki:singe_searching#colmodel_options). The usage of jQuery.datepicker in jqGrid is very easy, but it makes your program more comfortable.
Usage of standard date formatter (formatter: 'date') can be useful to convert source data format send to jqGrid to the new format which will be displayed. For example,
formatter: 'date', formatoptions: {srcformat:'y-m-d', newformat: 'Y-M-d' }
It is less interesting, but it can reduce a little the size of data send from server to client.
UPDATED: I must admit, I don't tested my suggestion with exactly your data format. Just now I tested all one more time and then read carefully jqGrid documentation about datefmt (see http://www.trirand.com/jqgridwiki/doku.php?id=wiki:colmodel_options). For datefmt are only numerical format for months is supported! So the value at the time of date verification must be in a numerical format. What can we do? For example following
we define as parameters of navGrid function "add" parameters (see http://www.trirand.com/jqgridwiki/doku.php?id=wiki:navigator parameter prmAdd) like following:
{ beforeCheckValues: function(posdata, formid, mode) {
var data = posdata.Date;
var dateParts = data.split("-");
var mounth = dateParts[1];
var mounths = $.jgrid.formatter.date.monthNames;
var iMounth = -1;
for (var i=0; i<12; i++) {
if (mounth === mounths[i]) {
iMounth = i;
break;
}
}
if (iMounth !== -1) {
posdata.Date = dateParts[0]+'-'+(iMounth+1)+'-'+dateParts[2];
}
},
beforeSubmit: function(postdata, formid) {
var data = postdata.Date;
var dateParts = data.split("-");
var mounths = $.jgrid.formatter.date.monthNames;
postdata.Date = dateParts[0]+'-'+
$.jgrid.formatter.date.monthNames[dateParts[1]-1]+
'-'+dateParts[2];
return [true,""];
}
}
So we convert the Date field to the numerical format inside of beforeCheckValues function and then convert all back to the original format (like 2010-Jan-23) after usage of checkDate. It will work.
The main question is now: have we some advantage from such kind of the date checking? We can just don't use editrules: { date:true } and implement our own date checking inside of beforeSubmit function. If we find out the wrong date we should return [false,"My error message"] and our custom error message "My error message" will be displayed by jqGrid.
So the easiest solution of your problem we receive if we could change the date format to any numerical form (Y-mm-d, mm/d/Y or another one). Usage of datepicker will makes for users the format problem not very important. Think about this and choose the way which your prefer.
I was facing similar issue. I have resolved it using custom function for validation. I am suing date format as '23-Jan-05'. You may modify it to suit your required date format.
function datecheck(value, colname) {
var dateParts = value.split("-");
var datePart = dateParts[0];
var mounth = dateParts[1];
var yearPart = dateParts[2];
var mounths = $.jgrid.formatter.date.monthNames;
var monthPart = -1;
for (var i = 0; i < 12; i++) {
if (mounth === mounths[i]) {
monthPart = i + 1;
break;
}
}
var dateText = monthPart + '-' + datePart + '-' + yearPart;
var date = Date.parse(dateText);
if (isNaN(date))
return [false,"Invalid date. Format expected: dd-mmm-yy. (23-Jul-05)"];
else
return [true,""];
}
JQGrid column details:
colModel: [name: 'JoiningDate', align: "center", editable: true,
editrules: { custom: true, custom_func: datecheck },
formatter: 'date', formatoptions: { srcformat: 'y-m-d', newformat: 'd-M-y' }, edittype: 'text', editable: true,
editoptions: { dataInit: function (el) { setTimeout(function () { $(el).datepicker({ dateFormat: 'd-M-y' }); }, 200); } }
},
Hope this helps.
Regards,
Abhilash