I understand the problem very good. I agree that both predefined formatter which one can use currently ('showlink' and 'link' formatters) are not flexible enough.
I can suggest you another formatter which you could download here. The usage of the formatter is very easy:
{label: "AddToCart", name: "Addtocrt_addtocrt", formatter: "dynamicLink",
formatoptions: {
url: function (cellValue, rowId, rowData) {
return '/Store/AddToCart' + rowId + '?' +
$.param({
quantity: rowData.Stocks_valkogus
});
}
}
}
The url
defined as function will be used in the <a>
as the value of href
attribute.
Additionally to the url
formatoptions
the 'dynamicLink' formatter supports target
option (with the same meaning as by 'showlink'), cellValue
which can be also function and onClick
callback with rowId
, iRow
, iCol
, cellValue
, e
as parameters. If the onClick
callback is defined the value of url
will be ignored. So one can skip the definition of the formatter option url
.
The demo demonstrate the usage of the 'dynamicLink' formatter:
The current code of the formatter: 'dynamicLink'
you can find below:
/*global jQuery */
(function ($) {
'use strict';
/*jslint unparam: true */
$.extend($.fn.fmatter, {
dynamicLink: function (cellValue, options, rowData) {
// href, target, rel, title, onclick
// other attributes like media, hreflang, type are not supported currently
var op = {url: '#'};
if (typeof options.colModel.formatoptions !== 'undefined') {
op = $.extend({}, op, options.colModel.formatoptions);
}
if ($.isFunction(op.target)) {
op.target = op.target.call(this, cellValue, options.rowId, rowData, options);
}
if ($.isFunction(op.url)) {
op.url = op.url.call(this, cellValue, options.rowId, rowData, options);
}
if ($.isFunction(op.cellValue)) {
cellValue = op.cellValue.call(this, cellValue, options.rowId, rowData, options);
}
if ($.fmatter.isString(cellValue) || $.fmatter.isNumber(cellValue)) {
return '<a' +
(op.target ? ' target=' + op.target : '') +
(op.onClick ? ' onclick="return $.fn.fmatter.dynamicLink.onClick.call(this, arguments[0]);"' : '') +
' href="' + op.url + '">' +
(cellValue || ' ') + '</a>';
} else {
return ' ';
}
}
});
$.extend($.fn.fmatter.dynamicLink, {
unformat: function (cellValue, options, elem) {
var text = $(elem).text();
return text === ' ' ? '' : text;
},
onClick: function (e) {
var $cell = $(this).closest('td'),
$row = $cell.closest('tr.jqgrow'),
$grid = $row.closest('table.ui-jqgrid-btable'),
p,
colModel,
iCol;
if ($grid.length === 1) {
p = $grid[0].p;
if (p) {
iCol = $.jgrid.getCellIndex($cell[0]);
colModel = p.colModel;
colModel[iCol].formatoptions.onClick.call($grid[0],
$row.attr('id'), $row[0].rowIndex, iCol, $cell.text(), e);
}
}
return false;
}
});
}(jQuery));
I plan to place the code of the formatter and some other plugins to jqGrid on the github.
UPDATED: Free jqGrid extends the options of formatter: "showlink"
(see the wiki article and the answer). So one don't need to use the formatter: "dynamicLink"
in case of usage free jqGrid.