How to apply column template after jqgrid is creat

2020-04-21 09:25发布

问题:

Free jqgrid does not allw to apply column template after it is created. I tried

  var newOrderPriceTemplate = {
    align: "center",
    formatter: "showlink",
    formatoptions: {
        onClick: function() { alert('clicked'); }
    }
    };

    $(function () {
      ... code to create jqgrid into $grid
      $grid.jqGrid('setColProp', 'Hind', {
        template: newOrderPriceTemplate,
        search: false
    }); 
    });

alert box does not appear if clicked in column. search: false removes search field properly so setColProp is executed.

How to apply newOrderPriceTemplate after jqgrid is created but before displayed. If template is specified in colModel at creation time, it works.

Latest free jqgrid, jquery, bootstrap 3, aps.net mvc4 , .net 4.6 are used.

回答1:

I think that there are misunderstanding how templates works. Template is nothing more as the list of settings which will be used in $.extend to combine some current properties from colModel with another object of template properties.

I recommend to read the code fragment of the code of free jqGrid. In simplified form the code looks like

for (iCol = 0; iCol < p.colModel.length; iCol++) {
    p.colModel[iCol] = $.extend(true, {},
        p.cmTemplate,
        p.colModel[iCol].template || {},
        p.colModel[iCol]);
}

In other words jqGrid combines the values from cmTemplate, template property of the column with the property of colModel. jqGrid does it at the beginning of creating the grid.

Thus if you have some template (newOrderPriceTemplate for example), which you need to apply after the grid is created, then you need just use $.extend manually to extend (and overwrite) the existing properties:

var p = $grid.jqGrid("getGridParam");

p.colModel[p.iColByName.Hind] = $.extend(true, {},
    p.colModel[p.iColByName.Hind], // old values
    newOrderPriceTemplate,         // the applied template
    { search: false }              // one more setting to apply
);

It's important to place new properties after the current settings from p.colModel[p.iColByName.Hind] to be able to overwrite there.