jqGrid动态更改特定行的edittype [英] jqGrid change dynamically edittype for specific row

查看:158
本文介绍了jqGrid动态更改特定行的edittype的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

遵循此帖子在找到想要实现的方法的地方,遇到了一些麻烦. 这是我的代码:

Following to this post where I found some way to do that I would want to get, I meet some trouble with it. Here is my code :

var myDlg = $("#dlgpers"),lastsel;
myDlg.jqGrid({
    url:'pers.php?id='+dataRow.id,
    mtype:'GET',
    datatype: "json",
    ajaxGridOptions: { cache: false },
    height:250,
    cmTemplate: {sortable:false},
    gridview: true,
    cellEdit:true,
    scroll:false,
    colNames:['Id','Label','Information','Type','Data'],
    colModel:[ 
        {name:'id',index:'id',hidden:true,key:true},
        {name:'label',index:'label',align:'right',width:100,editable:false,
            cellattr: function (rowId, val, rawObject, cm, rdata) {
                return ' style="font-weight:bold;margin-right:5px;border-left:0;border-top:0;" class="ui-state-active"' ;
            }
        },
        {name:'info',index:'info',width:200,editable:true,edittype:'text'},
        {name:'type',index:'type',width:30,hidden:true},
        {name:'data',index:'data',width:30,hidden:true}
    ],
    loadComplete: function () {
        var rowIds = myDlg.jqGrid('getDataIDs');
        $.each(rowIds, function (i, row) {
            var rowData = myDlg.jqGrid('getRowData',row);
            if (rowData.type == 'select') {
                myDlg.jqGrid('restoreRow', row);
                var cm = myDlg.jqGrid('getColProp', 'info');
                cm.edittype = 'select';
                cm.editoptions = { value: rowData.data };
                myDlg.jqGrid('editRow', row);
                cm.edittype = 'text';
                cm.editoptions = null;
                cm.editable = true;
            }else{
                myDlg.jqGrid('restoreRow', row);
                var cm = myDlg.jqGrid('getColProp', 'info');
                cm.edittype = 'text';
                cm.editoptions = null;
                cm.editable = true;
                myDlg.jqGrid('editRow', row);
                cm.edittype = 'text';
                cm.editoptions = null;
                cm.editable = true;
            }
        });
    }
});

,结果显示为图像:

和JSON响应:

{"page":1,"total":1,"records":1,"rows":[
{"cell":[0,"Nom ","LEBRUN","text",""]},
{"cell":[1,"Pr\u00e9nom ","Jacques","text",""]},
{"cell":[2,"Initiales ","LJ","text",""]},
{"cell":[3,"Fonction ","","text",""]},
{"cell"[4,"Service,"Administratif","select","0:Administratif;1:Commercial;2:Magasin;3:M\u00e9canique;4:Rejointage;5:Soudure;6:Tests"]},
{"cell":[5,"T\u00e9l\u00e9phone ","","text",""]},
{"cell":[6,"Email ","","text",""]},
{"cell":[7,"Statut ","CDI","select","0:CDI;1:CDD;2:App;3:Stg;4:Int"]},
{"cell":[8,"Entr\u00e9 le ","2008-10-06","text",""]},
{"cell":[9,"Sorti le ","0000-00-00","text",""]}]}

我向您提供了两个问题:

Two questions I submit to your knowledge:

  1. 如您所见,第二行(Prénom)似乎不可编辑,但是它是可编辑的.
  2. 我不明白为什么这些输入是可见的,因为我希望它们只有在编辑某些单元格时才会显示.

非常感谢您的所有帮助,以解决(并解释)我的错误方法. 吉禾L

Many thanks for all your kind help for resolve (and explain) my wrong way. JiheL

更新了2013-03-29

我已经应用了您的答案代码,并且运行正常!非常感谢. 但是我以另一种方式创建了另一种形式,这给我带来了一些麻烦.

I have applied your answer code and that run fine ! Many thanks. But I have created another form in such a way for another subject, and that cause me some troubles.

这是这种新形式的代码:

Here is the code of this new form :

        var showAbs=function(){
        $('#EditDialog').empty();
        var $table=$('<table></table>')
        .attr('id','dlgcong')
        .appendTo($('#EditDialog'));
        var myCong = $("#dlgcong");
        myCong.jqGrid({
            url:'xpabs.php?id='+id+'&y='+y,
            datatype: "json",
            height:"auto",
            cmTemplate: {sortable:false},
            gridview: true,
            colNames:['Type absence','Début','Fin','id'],
            colModel:[ 
                {name:'abs',index:'abs',width:155,editable:true,edittype:'select',
                    editoptions:{ 
                        dataUrl:"selabs.php", 
                    dataEvents: [
                            {
                                type: 'change',
                                fn: function(e) {
                                    $(this).parent().css('background-color','#'+$(this).find('option:selected').attr('colr'));
                                    if($(this).find('option:selected').attr('colr')=='ffffff'){
                                        $(this).parent().parent().find('input').datepicker('disable');
                                    }else{
                                        $(this).parent().parent().find('input').datepicker('enable');
                                        $(this).parent().parent().attr('changed',true);
                                    }
                                }
                            }
                        ]
                    },
                    cellattr: function (rowId, val, rawObject, cm, rdata) {
                        return ' style="background-color:#'+rawObject[4]+';color:white;"';
                    }
                },
                {name:'debut',index:'debut',align:'center',width:70,editable:true},
                {name:'fin',index:'fin',align:'center',width:70,editable:true},
                {name:'id',index:'id',hidden:true}
            ],
            jsonReader: {
                cell: "", 
                root: function (obj) { 
                    return obj; 
                } 
            },                  
            loadComplete: function (data) {
                var $self = $(this),
                        cm = $self.jqGrid("getColProp", "debut"),
                        idPrefix = $self.jqGrid("getGridParam", "idPrefix"),
                        l = data.length,
                        i,
                        item;
                for (i = 0; i < l; i++) {
                    item = data[i];
                    cm.editoptions = {
                        dataInit: function(element) {
                            $(element).datepicker({
                                setDate:item[1],
                                minDate:'01/01/'+y,
                                maxDate:'31/12/'+y,
                                onSelect: function( selectedDate,inst ) {
                                    $(element).val(selectedDate );
                                    $(element).parent().parent().attr('changed',true);
                                }
                            })
                        }
                    }
                }
                var cm = $self.jqGrid("getColProp", "fin");
                for (i = 0; i < l; i++) {
                    item = data[i];
                    cm.editoptions = {
                        dataInit: function(element) {
                            $(element).datepicker({
                                setDate:item[2],
                                minDate:'01/01/'+y,
                                maxDate:'31/12/'+y,
                                onSelect: function( selectedDate,inst ) {
                                    $(element).val(selectedDate );
                                    $(element).parent().parent().attr('changed',true);
                                }
                            })
                        }
                    }
                    $self.jqGrid("editRow", idPrefix + item[3]);
                }
                myCong.find('select').each(function(){
                    $(this).css({
                        backgroundColor:'transparent',
                        color:'white',
                        border:0,
                        width:155
                    });
                });
            },
            idPrefix: "cong",
            rowNum: 10000   
        });
        //********************
        //  Button ' Valider '
        //********************
        $('<input />')
        .attr({
            type:'button',          
        })
        .css({
            float:'right',
            marginTop:'5px'
        })
        .click(function(){
            var toBeSaved='';
            myCong.find('tr[changed=true]').each(function(idx){
                if(toBeSaved.length>0){
                    toBeSaved+='|';
                }
                toBeSaved+=$(this).find('td:eq(3)').text()+';';
                toBeSaved+=$(this).find('select option:selected').val()+';';
                toBeSaved+=$(this).find('input:eq(0)').val()+';';
                toBeSaved+=$(this).find('input:eq(1)').val();
            });
            if(toBeSaved.length>0){
                $.ajax({
                    url:'majpabs.php?id='+id+'&data='+toBeSaved,
                    async:false,
                    dataType:'json',
                    success:function(data){
                        myGrid.trigger('reloadGrid');
                        $('#newAbs').val(' Nouveau ').attr('disabled',false);
                    }
                });
            }
        })
        .val(' Valider les absences ')
        .appendTo($('#EditDialog'));
        //*******************
        //  Button ' Retour '
        //*******************
        $('<input />')
        .attr({
            type:'button',
            id:'newAbs'
        })
        .css({
            float:'left',
            marginTop:'5px'
        })
        .click(function(){
            showPers();
        })
        .val(' Retour ')
        .appendTo($('#EditDialog'));
        //********************
        //  Button ' Nouveau '
        //********************
        $('<input />')
        .attr({
            type:'button',
            disabled:false
        })
        .css({
            float:'left',
            marginTop:'5px',
            marginLeft:'7px'
        })
        .click(function(){
            if($(this).val()==' Nouveau '){
                var myRow = {abs:"0", debut:'00/00/'+y, fin:'00/00/'+y, id:'0'};
                myCong.jqGrid('addRowData','',myRow, 'last');
                $(this).val(' Sauver ').attr('disabled',true);
            }else{
            }
        })
        .val(' Nouveau ')
        .appendTo($('#EditDialog'));
    }

,结果显示为图像:

  1. 如您所见,第一行不像其他行那样接收select和datepicker.奇怪!
  2. 当我添加新行时,它不接收select和datepicker作为第一行. 我认为我对这种方法的理解是错误的.
  1. As you can see, the first row does not receive select and datepicker as other rows. Strange !
  2. When I add new row, it does not receive select and datepicker as the first row. I think I'm wrong in understanding this method.

我担心打扰您这些问题,我在Wiki上浏览时没有成功找到找到使这些观点正确的任何方法.我想找到一些更详细的教程,其中显示了一些案例示例.

I'm worry to bother you with these questions, I had a look in wiki without success to find any way to make these points correct. I would like to find some more detailed tutorial which show some cases examples.

谢谢非常,如果您能再花一些时间给我一种使用jqGrid.JiheL的效率更高的方法

Thank you VERY MUCH if you can spend again some time for give me a way to be more efficient with jqGrid.JiheL

已更新2013-04-01

我已经应用了Oleg的建议,现在可以使用了.但是麻烦仍然存在. 这是图片:

I have applied Oleg's suggestions and that works now. But a trouble remains. here is the image :

对于第一行,选择框为确定". 第一个输入字段接收datepicker,但第二个输入字段(称为"fin"的列)不接收! 所有其他行都接收良好的日期选择器,但不接收第一行的最后一个字段. 这是代码:

For the first row, select box is OK. The first input field receive datepicker, but the second (the column called 'fin') not ! All others rows receive well datepickers, but not the last field of first row. Here is the code :

                loadComplete: function (data) {
                var $self = $(this),
                        idPrefix = $self.jqGrid("getGridParam", "idPrefix"),
                        l = data.length,
                        i,
                        item,
                        cm;
                for (i = 0; i < l; i++) {
                    item = data[i];
                    cm = $self.jqGrid("getColProp", "debut");
                    cm.editoptions = {
                        dataInit: function(element) {
                            //alert('deb'+i);
                            $(element).datepicker({
                                setDate:item[1],
                                minDate:'01/01/'+y,
                                maxDate:'31/12/'+y,
                                onSelect: function( selectedDate,inst ) {
                                    $(element).val(selectedDate );
                                    $(element).parent().parent().attr('changed',true);
                                }
                            })
                        }
                    };
                    $self.jqGrid("editRow", idPrefix + item[3]);
                    //
                    cm = $self.jqGrid("getColProp", "fin");
                    cm.editoptions = {
                        dataInit: function(element) {
                            //alert('fin'+i);
                            $(element).datepicker({
                                setDate:item[2],
                                minDate:'01/01/'+y,
                                maxDate:'31/12/'+y,
                                onSelect: function( selectedDate,inst ) {
                                    $(element).val(selectedDate );
                                    $(element).parent().parent().attr('changed',true);
                                }
                            })
                        }
                    };
                    $self.jqGrid("editRow", idPrefix + item[3]);
                }
                myCong.find('select').each(function(){
                    $(this).css({
                        backgroundColor:'transparent',
                        color:'white',
                        border:0,
                        width:155
                    });
                });
            },

下次,希望您能帮助我解决此问题并关闭此请求. 非常感谢您一直以来为新手提供的帮助. 吉禾L

Another time, I hope you can help me to resolve this trouble and close this request. Many thanks for all the time you spend to help newbies. JiheL

推荐答案

我认为您的代码中的许多问题都很常见.因此,我尝试着更详细地回答您的问题.

I think that many from the problems in your code common. So I tried to answer on you question more detailed.

首先,您发布了错误的JSON数据.线

First of all you posted wrong JSON data. The line

{"cell"[4,"Service,"Administratif","select","0:Administratif;1:Commercial;2:Magasin;3:M\u00e9canique;4:Rejointage;5:Soudure;6:Tests"]},

包含两个错误:

  1. 单元格"后没有':'
  2. "Service
  3. 之后没有"

更改后,行将保持不变

{"cell":[4,"Service","Administratif","select","0:Administratif;1:Commercial;2:Magasin;3:M\u00e9canique;4:Rejointage;5:Soudure;6:Tests"]},

和JSON数据可以读取.下一个问题是在一个数组中使用数字和字符串.因为该行中的错误jqGrid代码

and JSON data could be read. The next problem is the usage of numbers together with string in one array. Because the bug in the line of jqGrid code

idr = ccur !== undefined ? ccur[idn] || idr : idr;

id不能为整数0.我发布了有关错误的错误报告. 要使用jqGrid的现有代码解决此问题,您应该使用字符串而不是数字.例如,线

ids could not be integer value 0. I posted the bug report about the error. To fix the problem using existing code of jqGrid you should use strings instead of numbers. For example the line

{"cell":[0,"Nom ","LEBRUN","text",""]},

应更改为

{"cell":["0","Nom ","LEBRUN","text",""]},

不进行任何更改,您将有 id个重复项.前两行({"cell":[0,"Nom ","LEBRUN","text",""]}{"cell":[1,"Pr\u00e9nom ","Jacques","text",""]},)都将具有等于1而不是0和1的相同ID.这是您描述的问题的主要原因.

Without the changes you will have id duplicates. Both first lines ({"cell":[0,"Nom ","LEBRUN","text",""]} and {"cell":[1,"Pr\u00e9nom ","Jacques","text",""]},) will get the same id equal to 1 instead of 0 and 1. It was the main reason of the problem which you described.

此外,我将向您推荐以下内容:

Additionally I would recommend you the following:

  • 删除cellEdit:true选项.您稍后在代码中使用editRow.这意味着您使用内联编辑而不是单元格编辑,表示cellEdit:true.您不能将两种编辑模式合并在一个网格中.
  • height:250选项替换为height:"auto"
  • colModel中删除所有index属性.使用默认值(edittype:'text'editable:false)删除colModel的所有属性
  • 使用默认值(mtype:'GET'scroll:false)删除jqGrid的选项
  • JavaScript函数的所有参数都是可选.因此,例如,如果您不使用cellattr回调的任何参数,则可以将cellattr: function (rowId, val, rawObject, cm, rdata) {...}替换为cellattr: function () {...}
  • 回调loadComplete具有一个参数data,该参数可以为您提供从服务器返回的所有数据.因此,您无需使用getDataIDsgetRowData.数组data.rows可以直接使用.
  • 如果使用loadComplete回调的data参数,则可以从网格中删除不需要的'type''data'列.
  • 如果将有关id的信息放在'Label','Information'之后,则可以使用jsonReaderid属性,也可以从网格中删除隐藏的id列.例如,如果将id移到cell数组的最后,则可以使用jsonReader: {id: 4}并从网格中删除隐藏的id列.如果在jsonReader中另外添加了cell: ""属性,则可以从输入数据中删除"cell":.如果要使用定义为函数的jsonReaderroot属性(请参见
  • remove celltrue option. You use editRow later in the code. It means that you use inline editing instead of cell editing which means celltrue. You can't combine both editing modes in one grid.
  • replace height:250 option to height:"auto"
  • remove all index properties from colModel. Remove all properties of colModel with default values (edittype:'text', editable:false)
  • remove options of jqGrid with default values (mtype:'GET', scroll:false)
  • all parameters of functions in JavaScript are optional. So if you don't use for example any parameters of cellattr callback you can replace cellattr: function (rowId, val, rawObject, cm, rdata) {...} to cellattr: function () {...}
  • the callback loadComplete has one parameter data which can provide you all data which returned from the server. So you don't need to use getDataIDs and getRowData. The array data.rows can by directly used.
  • if you use data parameter of loadComplete callback you can remove unneeded 'type' and 'data' columns from the grid.
  • if you place information about id after 'Label','Information' then you can use id property of jsonReader and remove hidden id column from the grid too. For example if you move id as the last in the cell array you can use jsonReader: {id: 4} and remove hidden id column from the grid. If you add additionally cell: "" property in jsonReader you can remove "cell": from the input data. If you would use root property of jsonReader defined as function (see the documentation) you can remove some unneeded data from the server response.

例如,服务器可以生成简化的数据

For example the server can produce the simplified data

[
["Nom ","LEBRUN","text","","0"],
["Pr\u00e9nom ","Jacques","text","","1"],
["Initiales ","LJ","text","","2"],
["Fonction ","","text","","3"],
["Service","Administratif","select","0:Administratif;1:Commercial;2:Magasin;3:M\u00e9canique;4:Rejointage;5:Soudure;6:Tests","4"],
["T\u00e9l\u00e9phone ","","text","","5"],
["Email ","","text","","6"],
["Statut ","CDI","select","0:CDI;1:CDD;2:App;3:Stg;4:Int","7"],
["Entr\u00e9 le ","2008-10-06","text","","8"],
["Sorti le ","0000-00-00","text","","9"]
]

对应的jqGrid可能是

The corresponding jqGrid could be

$("#dlgpers").jqGrid({
    url: "pers.php?id=" + dataRow.id,
    datatype: "json",
    height: "auto",
    cmTemplate: {sortable: false},
    gridview: true,
    colNames: ["Label", "Information"],
    colModel: [
        {name: "label", align: "right", width: 100,
            cellattr: function () {
                return ' style="font-weight:bold;margin-right:5px;border-left:0;border-top:0;" class="ui-state-active"';
            }},
        {name: "info", width: 200, editable: true}
    ],
    jsonReader: {id: 4, cell: "", root: function (obj) { return obj; } },
    loadComplete: function (data) {
        var $self = $(this),
            cm = $self.jqGrid("getColProp", "info"),
            idPrefix = $self.jqGrid("getGridParam", "idPrefix"),
            l = data.length,
            i,
            item;

        for (i = 0; i < l; i++) {
            item = data[i];
            cm.edittype = item[2] === "select" ? "select" : "text";
            cm.editoptions = { value: item[3] };
            $self.jqGrid("editRow", idPrefix + item[4]);
        }
    },
    idPrefix: "dlg",
    rowNum: 10000 // to have no paging
});

请参见演示:

这篇关于jqGrid动态更改特定行的edittype的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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