用jqgrid加载数据后是否可以修改colModel? [英] Is it possible to modify the colModel after data has loaded with jqgrid?

查看:99
本文介绍了用jqgrid加载数据后是否可以修改colModel?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个jqGrid,在加载数据之后但在将其解析为网格之前,我需要在其中更改模型.换句话说,我想我想在loadComplete处理程序中执行此操作.我看到了这种方法:根据JSON数据设置JqGrid的colName和colModel ,但是我已经编写了许多网格,这些网格使用使用jqGrid加载数据"方法,而不是使用那里的预加载数据并将其传递给jqGrid",我希望避免重新-编码,或对此进行更改.

I've got a jqGrid where I need to change the model after the data is loaded, but before it's parsed into the grid. In otherwords, I think I want to do it in the loadComplete handler. I see this approach: Setting JqGrid's colName and colModel from JSON data, but I'm have a bunch of grids already written that use the "load data with jqGrid" approach, rather than the "pre-load data and pass it to jqGrid" one used there, and I'm hoping to avoid re-coding, or making this one different.

(隐藏和显示隐藏的列也不可行.)

(Hiding and showing hidden columns isn't practical, either.)

这可能吗?

更多详细信息:

基本上,直到看到数据,我才知道需要哪些列.假设我正在按州显示流量:

Basically, I don't know what columns I need till I see the data. Say I'm showing traffic by state:

Date      CA     WA     NY    MN
4/20      100    90     85    72
4/21       95    85     89    70

只有一个空间可以显示四个状态,但是数据中可能有更多的状态(或者可能更少),所以我希望按流量顺序列出它们.现在,数据输入如下:

There's only room to show four states, but there might be many more in the data (or there might be fewer), so I want them listed in order of traffic. Right now, the data is coming in like:

{
date : 4-20,
ca : 100,
wa : 90,
ny : 85,
mn : 72
hi : 56,
il : 30
},
{
date : 4-21,
ca : 95,
wa : 85, // note: for a given row, a column might be relatively lower
ny : 89, // than another. The column order is based on the overall
mn : 70
hi : 60,
il : 45
}

或者可能是:

{
date : 4-20,
ny : 110,
hi : 95,
il : 90,
wa : 80
}

我尝试设置诸如state1,state2,state3,state4之类的列,然后使用jsonmap对其进行重新映射,但这没有用.

I've tried setting up columns like state1, state2, state3, state4 and then using jsonmap to remap them, but it didn't work.

loadonce = true,数据类型= json

loadonce = true, datatype = json

推荐答案

我找到了一种看起来可行的方法.

I found one way which seems work OK.

以下是我的解决方案的想法.您使用colModel具有许多隐藏列,这些隐藏列的虚拟名称为'cm0','cm1','cm2',....所有列都具有与您所需要的数据相同的数据.为了更轻松地填充数据,我使用自jqGrid 3.8.2起存在的列模板:

The idea of my solution is following. You use colModel having many hidden columns with the dummy names like 'cm0', 'cm1', 'cm2', ... All the columns has the same data like you need in your case. To fill the data more easy I use column templates existing since jqGrid 3.8.2:

var mygrid=jQuery("#list"),
    cmIntTemplate = {
        width:50,
        sorttype:"int",
        formatter:"integer",
        align:"right",
        hidden:true
    },
    cm = [
        // here we define the first columns which we always has
        // the list can be empty or has some columns with
        // the properties other as the rest (without cmIntTemplate)
        {name:"date",label:"Date",key:true,width:100, fixed:true,
         formatter:'date',formatoptions:{srcformat:"m-d",newformat:"m/d"}}
    ], maxCol = 30, dummyColumnNamePrefix = "cm";

// Add dummy hidden columns. All the columns has the same template
for (i=0;i<maxCol;i++) {
    cm.push({name:dummyColumnNamePrefix+i,template:cmIntTemplate});
}

之后,我以标准方式创建jqGrid,但使用jsonReader并使用page

After that I create jqGrid in the standard way, but with the jsonReader which use the page as function:

jsonReader: {
    repeatitems: false,
    page: function (obj) {
        // ------------------------
        // here I add the main code
        // ------------------------
        return obj.page;
    }
}

jsonReader.page中的函数返回的值与默认值jsonReader相同,但是我使用了function的方式,因为该函数将在读取JSON数据的主要内容之前直接调用.在代码内部,获取数据的第一行,并使用其属性名称填充相应列的jsonmap属性并设置列名称.另外,我需要一些虚拟列以显示所有JSON数据,而其余虚拟列则隐藏.最后要做的是校正先前计算出的网格宽度.因此网格将如下所示:

The function from the jsonReader.page return the same value like as do default jsonReader, but I use the way with function because the function will be called directly before the reading of the main contain of JSON data. Inside of the code I get the first row of the data and use it's property names to fill jsonmap property of the corresponding column and set the column name. Additionally I make some dummy columns needed to display all the JSON data visible and the rest dummy column hidden. The last thing which should be done is correction of the grid width which was calculated previously. So the grid will look like this:

或类似的

取决于JSON输入数据.

depend on the JSON input data.

page函数的代码如下:

page: function (obj) {
    var rows = obj.rows, colModel = mygrid[0].p.colModel,
        cmi, iFirstDummy, firstRow, prop,
        orgShrinkToFit, isFound,
        showColNames = [], hideColNames = [];

    if (typeof(rows) === "undefined" || !$.isArray(rows) || rows.length === 0) {
        // something wrong need return
        return obj.page;
    }

    // find the index of the first dummy column
    // in the colModel. If we use rownumbers:true,
    // multiselect:true or subGrid:true additional
    // columns will be inserted at the begining
    // of the colModel
    iFirstDummy = -1;
    for(i=0;i<colModel.length;i++) {
        cmi = colModel[i];
        if (dummyTestRegex.test(cmi.name)) {
            iFirstDummy = i;
            break;
        }
    }
    if (iFirstDummy === -1) {
        // something wrong need return
        return obj.page;
    }

    orgShrinkToFit = clearShrinkToFit();

    // we get the first row of the JSON data
    firstRow = rows[0];
    for (prop in firstRow) {
        if (firstRow.hasOwnProperty(prop)) {
            // we will use the properties name of the first row
            // as the names of the column headers of the grid

            // find column index having prop as the name
            isFound = false;
            for(i=0;i<colModel.length;i++) {
                cmi = colModel[i];
                if (cmi.name === prop) {
                    isFound = true;
                    showColNames.push(prop);
                    break;
                }
            }
            if(!isFound) {
                // labels defines the column names
                cmi = colModel[iFirstDummy];
                showColNames.push(cmi.name);
                mygrid.jqGrid('setLabel',cmi.name,prop);

                // because of bug in jqGrid with calculation of width
                // we have to reset the width
                cmi.width = cmIntTemplate.width;

                // we set jsonmap which jqGrid will use instead
                // of dummy column names to read all row data
                cmi.jsonmap = prop;
                iFirstDummy++;
            }
        }
    }

    // fill the list of unused columns
    for(i=0;i<colModel.length;i++) {
        cmi = colModel[i];
        if ($.inArray(cmi.name, showColNames) === -1 && dummyTestRegex.test(cmi.name)) {
            hideColNames.push(cmi.name);
        }
    }
    mygrid.jqGrid('showCol',showColNames);
    mygrid.jqGrid('hideCol',hideColNames);

    setGridWidthAndRestoreShrinkToFit(orgShrinkToFit);

    return obj.page;
}

page函数内部,我使用了小的辅助函数

Inside of the page function I use small helper functions

var clearShrinkToFit = function() {
        // save the original value of shrinkToFit
        var orgShrinkToFit = mygrid.jqGrid('getGridParam','shrinkToFit');
        // set shrinkToFit:false to prevent shrinking
        // the grid columns after its showing or hiding
        mygrid.jqGrid('setGridParam',{shrinkToFit:false});
        return orgShrinkToFit;
    },
    setGridWidthAndRestoreShrinkToFit = function(orgShrinkToFit) {
        // calculate the new grid width
        var width=0, i=0, headers=mygrid[0].grid.headers, l=headers.length;
        for (;i<l; i++) {
            var th = headers[i].el;
            if (th.style.display !== "none") {
                width += $(th).outerWidth();
            }
        }

        // restore the original value of shrinkToFit
        mygrid.jqGrid('setGridParam',{shrinkToFit:orgShrinkToFit});

        // set the grid width
        mygrid.jqGrid('setGridWidth',width);
    },
    dummyTestRegex = new RegExp(dummyColumnNamePrefix+"(\\d)+");

可以在此处看到的工作演示.

The working demo you can see here.

更新:另一个答案演示一起展示了如何创建具有另一种格式的网格输入数据:[[],[],...](数组数组)-矩阵.

UPDATED: Another answer with the demo shows how to create the grid which has another format of input data: [[], [], ...] (array of arrays) - matrix.

这篇关于用jqgrid加载数据后是否可以修改colModel?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆