如何在jqgrid中添加新行后触发loadComplete?

时间:2012-12-07 10:26:46

标签: jquery jqgrid

我有一个自定义格式化程序,可以在jqgrid的loadComplete中激活。在动态添加行时,需要使用相同的自定义格式化程序。所以我想像任何正常的函数一样调用loadComplete()。自定义格式化程序在加载网格时运行良好,但在以后添加行时不会生效。

动态添加行

function addRow(cfgid,cfgname,hostname,osname,cfgDesc,productId,cfgType,updateDate,emailAddress,absolutePath,fileName,productVersion,converted)
{

    var myrow = {cfgId:cfgid, '':'', cfgName:cfgname, hostname:hostname, osname:osname, cfgDesc:cfgDesc, productId:productId,hostname:hostname,cfgType:cfgType,updateDate:updateDate,emailAddress:emailAddress,absolutePath:absolutePath,fileName:fileName,productVersion:productVersion,converted:converted};

    $("#list1").addRowData(cfgid, myrow,"first");
    //$("#list1").loadComplete(); does not work
    $("#list1").trigger("reloadGrid");
    $("#list1").sortGrid('updateDate', true, 'desc');

}

的jqGrid

function drawDynamicGrid(xml)
{
    var emptyMsgDiv = $('<div>No configurations loaded</div>');

    var xmlObject=StringtoXML(xml);
    var getColumnIndexByName = function (grid, columnName) {
        var cm = grid.jqGrid('getGridParam', 'colModel'), i = 0, l = cm.length;
        for (; i < l; i += 1) {
            if (cm[i].name === columnName) {
                return i; // return the index
            }
        }
        return -1;
    },
    grid = jQuery("#list1"),
    convertIcon = '<span class="ui-state-default" style="border:0" id="converted"><span class="ui-icon ui-icon-info" style="float: left; margin-right: .3em;"></span></span>',
    iconAlert = '<span class="ui-state-error" style="border:0" id="expired"><span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;"></span></span>';
    grid.jqGrid({

      datastr : xml,
      datatype: 'xmlstring',
      colNames:['cfgId','Name', 'Host','Operating System', 'Description','Product', 'Type', 'Last Updated Time','Last Updated By','','','',''],
      colModel:[
          {name:'cfgId',index:'cfgId', width:90, align:"left", hidden:true},
          {name:'cfgName',index:'cfgName', width:80, align:"left", formatter: 'showlink', formatoptions: {baseLinkUrl: '#'} },
          {name:'hostname',index:'hostname', width:70, align:"left"},
          {name:'osname',index:'osname', width:90, align:"left"},
          {name:'cfgDesc',index:'cfgDesc', width:80, align:"left"},
          {name:'productId',index:'productId', width:40, align:"left"},
          {name:'cfgType',index:'cfgType', width:50, align:"left"},
          {name:'updateDate',index:'updateDate',sorttype:'Date', width:120, align:"left"},
          {name:'emailAddress',index:'emailAddress', width:120, align:"left"},
          {name:'absolutePath',index:'absolutePath', width:90, align:"left", hidden:true},
          {name:'fileName',index:'fileName', width:10, align:"left", hidden:true},
          {name:'productVersion',index:'productVersion', width:10, align:"left", hidden:true},
          {name:'converted',index:'converted', width:10, align:"left", hidden:true}
      ],
      pager : '#gridpager',
      rowNum:10,
      rowList:[10,50,100],
      scrollOffset:0,
      height: 'auto',
      emptyrecords: 'No configurations loaded',
      autowidth:true,
      viewrecords:true,
      gridview: true,
      multiselect: true,
      xmlReader: {
          root : "list",
          row: "Response",
          id: "cfgId",
          userdata: "userdata",
          repeatitems: false
      },

      loadComplete: function () {

            var count = grid.jqGrid('getGridParam');
            var ts = grid[0];
            if (ts.p.reccount === 0) {
                grid.hide();
                emptyMsgDiv.show();
            } else {
                grid.show();
                emptyMsgDiv.hide();
            }

            //for showlink and icon alert having date difference more than 90 days
            var iRow, row, trClasses, $cell,
            icfgName = getColumnIndexByName(grid, 'cfgName'),
            iupdateDate = getColumnIndexByName(grid, 'updateDate'),
            iconverted = getColumnIndexByName(grid, 'converted'),

            mygrid = grid[0],
            rows = mygrid.rows,
            cRows = rows.length,
            myLink = function (e) {
                var $td = $(e.target).closest('td'),
                    text = $td.text(),
                    $tr = $td.closest('tr'),
                    rowid = $tr[0].id;
                    goToViewAllPage(rowid);
            };
        for (iRow = 0; iRow < cRows; iRow += 1) {
            row = rows[iRow]; // row.id is the rowid
            trClasses = row.className.split(' ');
            if ($.inArray('jqgrow', trClasses) > 0) {
                // the row is a standard row (only if subGrid:true are used)
                var cellvalue1,firstDate,secondDate;
                $cell = $(row.cells[icfgName]);
                cellvalue1=$(row.cells[iupdateDate]).text();
                firstDate = new Date();
                //console.info(cellvalue1+", "+cellvalue1.length);
                //var cellvalue1="08-18-2011 11:49:01";
                var convertedText=$(row.cells[iconverted]).text();
                if(cellvalue1.length>25)
                {

                    secondDate=new Date();
                    //secondDate = secondDate.substring(0, secondDate.length-3);

                    if(diffOf2Dates(firstDate,secondDate,true)>=expireCondition)
                    {
                        $cell.prepend(iconAlert);
                    }
                    $cell.click(myLink);
                }
                else
                {
                    if(cellvalue1.length!=1)
                    {

                        secondDate = cellvalue1.substring(0, cellvalue1.length-6);
                        if(diffOf2Dates(firstDate,secondDate,false)>=expireCondition)
                        {
                            $cell.prepend(iconAlert);
                        }
                        $cell.click(myLink);
                    }

                    //I want to add this Icon when a new row is added using addRowData
                    if(convertedText=="yes"&&supportEng)$cell.prepend(convertIcon);


                }
            }
        }

        }
    });
    grid.jqGrid('navGrid','#gridpager',{edit:false,add:false,del:false});

    var myGrid = $("#list1");
    $("#cb_"+myGrid[0].id).hide();
    // place div with empty message insde of bdiv
    emptyMsgDiv.insertAfter(grid.parent());

    $("#list1").trigger("reloadGrid");
    $("#list1").sortGrid('updateDate', true, 'desc');
    $("#list1").setGridParam({rowNum:10});

}

更新

服务器响应

<list>
  <Response>
    <cfgId>1223</cfgId>
    <cfgName>ld</cfgName>
    <cfgDesc>fhdf</cfgDesc>
    <cfgType>Production</cfgType>
    <fileName>4.xml</fileName>
    <absolutePath>../../../xmlrepository/121/4_ver3.xml</absolutePath>
    <emailAddress>mk@aol.com</emailAddress>
    <projectId>121</projectId>
    <hostname>abc-dev-01.24hourfit.com</hostname>
    <createDate>2012-12-07 12:15:48.0 IST</createDate>
    <updateDate>2012-12-07 12:15:48.0 IST</updateDate>
    <state>1</state>
    <productId>3</productId>
    <osname>Linux</osname>
    <productVersion>1.0 HotFix5</productVersion>
    <converted>yes</converted>
  </Response>
  <Response>
    <cfgId>1224</cfgId>
    <cfgName>DD</cfgName>
    <cfgDesc>dfsd</cfgDesc>
    <cfgType>Production</cfgType>
    <fileName>2.xml</fileName>
    <absolutePath>../../../xmlrepository/121/2_ver1.xml</absolutePath>
    <emailAddress>mk@aol.com</emailAddress>
    <projectId>121</projectId>
    <hostname>vkeh-jam</hostname>
    <createDate>2012-12-07 12:21:31.0 IST</createDate>
    <updateDate>2012-12-07 12:21:31.0 IST</updateDate>
    <state>1</state>
    <productId>3</productId>
    <osname>HP-UX</osname>
    <productVersion>5.0</productVersion>
    <converted>no</converted>
  </Response>
</list>

goToViewAllPage函数

function goToViewAllPage(rowid)
{
    var pageLoadContent='<table id="detailTable" width="100%"><tbody><tr><td align="center">Please Wait</td></tr><tr><td align="center"><img src="/informaticaCSM/infa9/csm/view/include/images/loading.gif" alt="Loading"/></td></tr></tbody></table>';
    //rowid=rowid.substring(4, rowid.length);
    $("#nextPageLoading").pageLoad({content:pageLoadContent});
    $("#nextPageLoading").css({"cursor":"wait"});
    $("#pageLoadingBackground").css({"cursor":"wait"});

    var rowData = jQuery("#list1").getRowData(rowid); 
    configid = rowData['cfgId'];
    configname=rowData['cfgName'];
    configdesc=rowData['cfgDesc'];
    configenv=rowData['cfgType'];
    filename=rowData['fileName'];
    updatedate=rowData['updateDate'];
    absolutepath=rowData['absolutePath'];
    productname=rowData['productId'];
    productversion=rowData['productVersion'];
    converted=rowData['converted'];

    //emailid=rowData['emailAddress'];
    emailid=logid;

    var form_ref=document.createElement("form");
    form_ref.id="viewform";
    form_ref.name="viewform";
    form_ref.action=redirectMainUrl+"showResult.action";
    form_ref.method="post";
    form_ref.target="_self";
    document.body.appendChild(form_ref);

    var cfgstField = document.createElement("input");
    cfgstField.name="sessiontoken";
    cfgstField.type="hidden";
    cfgstField.value=sessiontoken;
    form_ref.appendChild(cfgstField);

    var cfgidField = document.createElement("input");
    cfgidField.name="cfgid";
    cfgidField.type="hidden";
    cfgidField.value=configid;
    form_ref.appendChild(cfgidField);

    var cfgnameField = document.createElement("input");
    cfgnameField.name="cfgname";
    cfgnameField.type="hidden";
    cfgnameField.value=configname;
    form_ref.appendChild(cfgnameField);

    var cfgdescField = document.createElement("input");
    cfgdescField.name="cfgdesc";
    cfgdescField.type="hidden";
    cfgdescField.value=configdesc;
    form_ref.appendChild(cfgdescField);

    var cfgenvField = document.createElement("input");
    cfgenvField.name="cfgenv";
    cfgenvField.type="hidden";
    cfgenvField.value=configenv;
    form_ref.appendChild(cfgenvField);

    var cfgfileField = document.createElement("input");
    cfgfileField.name="cfgfile";
    cfgfileField.type="hidden";
    cfgfileField.value=filename;
    form_ref.appendChild(cfgfileField);

    var cfgabsField = document.createElement("input");
    cfgabsField.name="absFileName";
    cfgabsField.type="hidden";
    cfgabsField.value=absolutepath;
    form_ref.appendChild(cfgabsField);

    var cfgdateField = document.createElement("input");
    cfgdateField.name="updatedDate";
    cfgdateField.type="hidden";
    cfgdateField.value=updatedate;
    form_ref.appendChild(cfgdateField);

    var cfgproductField = document.createElement("input");
    cfgproductField.name="productname";
    cfgproductField.type="hidden";
    cfgproductField.value=productname;
    form_ref.appendChild(cfgproductField);

    var cfgproductVersionField = document.createElement("input");
    cfgproductVersionField.name="productversion";
    cfgproductVersionField.type="hidden";
    cfgproductVersionField.value=productversion;
    form_ref.appendChild(cfgproductVersionField);

    var projectIdField = document.createElement("input");
    projectIdField.name="projectid";
    projectIdField.type="hidden";
    projectIdField.value=$("#projectId").val();
    form_ref.appendChild(projectIdField);

    var cfgprevPageField = document.createElement("input");
    cfgprevPageField.name="backpage";
    cfgprevPageField.type="hidden";
    cfgprevPageField.value=$("#backPage").val();
    form_ref.appendChild(cfgprevPageField);

    var hiddenEmailField = document.createElement("input");
    hiddenEmailField.setAttribute("type", "hidden");
    hiddenEmailField.setAttribute("name", "emailaddress");
    //hiddenEmailField.setAttribute("value", document.getElementById("usernamespan").innerHTML);
    hiddenEmailField.setAttribute("value", emailid);
    form_ref.appendChild(hiddenEmailField);

    var hiddenEmailField = document.createElement("input");
    hiddenEmailField.setAttribute("type", "hidden");
    hiddenEmailField.setAttribute("name", "fullemailid");
    hiddenEmailField.setAttribute("value", fullEmailId);
    form_ref.appendChild(hiddenEmailField);    

    var hiddenConvertedField = document.createElement("input");
    hiddenConvertedField.setAttribute("type", "hidden");
    hiddenConvertedField.setAttribute("name", "converted");
    hiddenConvertedField.setAttribute("value", converted);
    form_ref.appendChild(hiddenConvertedField);

    setTimeout(function(){
        form_ref.submit();
    }, 10);


}

1 个答案:

答案 0 :(得分:2)

我建议您将当前代码从loadComplete删除到自定义格式化程序。使用自定义格式化程序,cellattrrowattrgridview: true结合使用是填充网格的最有效方法。有关详细信息,请参阅the answer

您可以将'cfgName'列的定义更改为以下内容:

{name: 'cfgName', width: 80, classes: "myLink",
    formatter: function (cellValue, options, rowObject) {
        var converted = rowObject.converted === undefined ?
                $(rowObject).find(">converted").text(): rowObject.converted,
            updateDate = rowObject.updateDate === undefined ?
                $(rowObject).find(">updateDate").text(): rowObject.updateDate;
        return (isAlertedDate(updateDate) ? iconAlert: "") +
            (converted === "yes" ? convertIcon : "") +
            "<span>" + cellValue + "</span>";
    },
    cellattr: function () {
        return " title=\"Click here to go to ViewAllPage\"";
    }}

您可以在diffOf2Dates的实现中使用当前的isAlertedDate函数。此外,我建议不要使用链接(<a>)来使代码更容易。而不是我使用classes: "myLink",我定义了以下CSS

.myLink { text-decoration: underline; cursor: pointer; }

生成的网格看起来与以前完全一样:

enter image description here

要点击链接执行一些JavaScript代码(甚至点击包含链接的单元格),可以使用beforeSelectRowonCellSelect callback。例如

beforeSelectRow: function (rowid, e) {
    var iCol = $.jgrid.getCellIndex($(e.target).closest("td")[0]);
    if (this.p.colModel[iCol].name === 'cfgName') {
        //alert("GO!!!");
        goToViewAllPage(rowid);
        return false;
    }
}

您可以在the demo上看到我的意思。