How to pass additional variables to jqGrid formatter?

stawek picture stawek · Dec 13, 2011 · Viewed 11.1k times · Source

I'm trying to create some kind of reusable formatter for jqGrid column, I would like to create custom formatter where I'm able to pass additional data , something similar to this code:

function imageLinkFormatter(cellval,options,rowObject,icon,link_class,link_action){
     var img='<span class="ui-icon '+icon+' icon"><span/>';    
    var link='<a href="#'+link_action+'/id/'+rowObject.id+'" class="'+link_class+'" rel="'+rowObject.id+'">'+img+'</a>';
    return link;
    }

Answer

Oleg picture Oleg · Dec 13, 2011

It's probably a misunderstanding. The interface of the custom formatter is defined by jqGrid. To have additional parameters in the custom formatter you have to modify the source code of jqGrid.

The good news is that you don't really need to extend the standard custom formatter. Instead of that you want probably just share the code. So you can define the common code as the function like

function imageLinkFormatter(cellval, options, rowObject, icon, link_class, link_action) {
    var img = '<span class="ui-icon ' + icon + ' icon"><span/>';    
    var link = '<a href="#' + link_action + '/id/' + rowObject.id + '" class="' +
        link_class + '" rel="' + rowObject.id + '">' + img + '</a>';
    return link;
}

and call the function from the custom formatter of the different columns of the grid with additional parameters.

colModal: [
    {name: 'col1', formatter: function (cellvalue, options, rowObject) {
            return imageLinkFormatter(cellvalue, options, rowObject,
                'ui-icon-pencil', 'edit-link-class', 'Edit');
        }},
    {name: 'col2', formatter: function (cellvalue, options, rowObject) {
            return imageLinkFormatter(cellvalue, options, rowObject,
                'ui-icon-plus', 'add-link-class', 'Add');
        }},
    {name: 'col2', formatter: function (cellvalue, options, rowObject) {
            return imageLinkFormatter(cellvalue, options, rowObject,
                'ui-icon-trash', 'del-link-class', 'Delete');
        }},
    ...
]

Is it what you want?