2011-08-04 34 views
5

¿Cómo obtener todas las filas que se editan?Obtenga todas las filas editadas en jqgrid

Tengo los siguientes jqgird, donde los usuarios pueden editar las casillas de verificación de todos los registros. Cuando se hace clic en el botón Guardar, necesito saber cuáles son todos los registros editados, soy nuevo en jquery y jqgrid.

¿Alguien me puede ayudar?

Aquí es el jqGrid y HTML usando:

var customerCodesView  = {}; 
customerCodesView.customerCodesView = function() { 

$jq("#customerCodesTable").jqGrid(
     { 
      colNames : ['Cust #','Customer Name', '1', '2','3', '4', '5', '6','7', '8','9', '10', '11', '12', '13', '-1'], 

      colModel : [{name : 'customerNumber',index : 'baseCustomerNumber',width : 55, align :'center'}, 
         {name : 'customerName',index : 'storeName',width : 100, sorttype :'text', align :'center'}, 
         {name : 'creditCodesPermissions.1',index : 'codeOne',width : 40,align : "center", editable:true, edittype:'checkbox', editoptions: { value:"True:False"}, formatter: "checkbox", formatoptions: {disabled : false}}, 
         {name : 'creditCodesPermissions.2',index : 'codeTwo',width : 40,align : "center", editable:true, edittype:'checkbox', editoptions: { value:"True:False"}, formatter: "checkbox", formatoptions: {disabled : false}}, 
         {name : 'creditCodesPermissions.3',index : 'codeThree',width : 40,align : "center", editable:true, edittype:'checkbox', editoptions: { value:"True:False"}, formatter: "checkbox", formatoptions: {disabled : false}}, 
         {name : 'creditCodesPermissions.4',index : 'codeFour',width : 40,align : "center", editable:true, edittype:'checkbox', editoptions: { value:"True:False"}, formatter: "checkbox", formatoptions: {disabled : false}}, 
         {name : 'creditCodesPermissions.5',index : 'codeFive',width : 40,align : "center", editable:true, edittype:'checkbox', editoptions: { value:"True:False"}, formatter: "checkbox", formatoptions: {disabled : false}}, 
         {name : 'creditCodesPermissions.6',index : 'codeSix',width : 40,align : "center", editable:true, edittype:'checkbox', editoptions: { value:"True:False"}, formatter: "checkbox", formatoptions: {disabled : false}}, 
         {name : 'creditCodesPermissions.7',index : 'codeSeven',width : 40,align : "center", editable:true, edittype:'checkbox', editoptions: { value:"True:False"}, formatter: "checkbox", formatoptions: {disabled : false}}, 
         {name : 'creditCodesPermissions.8',index : 'codeEight',width : 40,align : "center", editable:true, edittype:'checkbox', editoptions: { value:"True:False"}, formatter: "checkbox", formatoptions: {disabled : false}}, 
         {name : 'creditCodesPermissions.9',index : 'codeNine',width : 40,align : "center", editable:true, edittype:'checkbox', editoptions: { value:"True:False"}, formatter: "checkbox", formatoptions: {disabled : false}}, 
         {name : 'creditCodesPermissions.10',index : 'codeTen',width : 40,align : "center", editable:true, edittype:'checkbox', editoptions: { value:"True:False"}, formatter: "checkbox", formatoptions: {disabled : false}}, 
         {name : 'creditCodesPermissions.11',index : 'codeEleven',width : 40,align : "center", editable:true, edittype:'checkbox', editoptions: { value:"True:False"}, formatter: "checkbox", formatoptions: {disabled : false}}, 
         {name : 'creditCodesPermissions.12',index : 'codeTwelve',width : 40,align : "center", editable:true, edittype:'checkbox', editoptions: { value:"True:False"}, formatter: "checkbox", formatoptions: {disabled : false}}, 
         {name : 'creditCodesPermissions.13',index : 'codeThirteen',width : 40,align : "center", editable:true, edittype:'checkbox', editoptions: { value:"True:False"}, formatter: "checkbox", formatoptions: {disabled : false}}, 
         {name : 'creditCodesPermissions.-1',index : 'codeMinusOne',width : 40,align : "center", editable:true, edittype:'checkbox', editoptions: { value:"True:False"}, formatter: "checkbox", formatoptions: {disabled : false}} 
         ], 

      pager : '#customerCodesTablePager', 
      rowNum : 1000, 
      loadOnce:true, 
      sortorder : "desc", 
      viewrecords : true, 
      gridview : true, 
      autowidth : true, 
      multiselect : true, 
      jsonReader : { 
       repeatitems : false, 
       root : function(obj) { 
        return obj; 
       }, 
       page : function(obj) { 
        return 1; 
       }, 
       total : function(obj) { 
        return 1; 
       }, 
       records : function(obj) { 
        return obj.length; 
       } 
      }, 
      sortable : true, 
      caption : "Credit Codes" 
     }); 

$jq("form#customerCodesForm").submit(
       function() { 
        var newUrl = resourceURL+"&action=searchCreditCodes&"+ $jq(this).serialize(); 
        $jq("#customerCodesTable").jqGrid("setGridParam", {"url" : newUrl,datatype : "json"}).trigger("reloadGrid"); 
        return false; 
       }); 

$jq(".submit").button({ 
    icons : { 
     primary : 'ui-icon-circle-zoomin' 
    } 
}); 

$jq("#customerCodesTableSave").click(function() { 

    var id = $jq("#customerCodesTable").jqGrid('getGridParam','selarrow'); 
    alert("save"); 
    if (id) { 
     var rowdata = $jq("#customerCodesTable").jqGrid('getRowData', id); 
     var postData = JSON.stringify(rowdata); 

     alert("postdata"+postData); 
    } 
    saveGrid(); 

}); 


function saveGrid() { 
    alert("saveGrid"); 
    var saveCollection = []; 
    //Collect all rows in editmode, the rows to be saved. 
    $.each($jq("#customerCodesTable").getDataIDs(), function (index, id) { 
     var row = grid.getInd(id, true); 
     if (row !== false) { 
      if ($(row).attr('editable') === '1') { 
       saveCollection.push(id); 
      } 
     } 
    }); 
    alert(""+saveCollection.toString() + "length" + saveCollection.length); 
} 

}; 

HTML:

<div id="customerCodes_Form"> 
    <form class="customerCodesForm" id="customerCodesForm" method="post"> 
    <fieldset class="ui-widget ui-widget-content ui-corner-all"> 
     <legend class="ui-widget ui-widget-header ui-corner-all">Permissions by Customer</legend> 
     <div> 
      <span> 
       <label for="customerNumber">Customer Number</label> 
       <input id="customerNumber" name="customerNumber" class=""/> 
      </span> 
      <button class="submit" type="submit">Search</button> 
     </div> 
    </fieldset> 
</form> 
<div id="customerCodesGrid"> 
    <table id="customerCodesTable"><tbody><tr><td></td></tr></tbody></table> 
    <div id="customerCodesTablePager"></div> 
    <div style="float:right;"> 
     <button id="customerCodesTableSave">Save</button> 
     <button id="customerCodesTableCancel">Cancel</button> 
    </div> 
</div> 
</div> 

Actualizado: @Justin Gracias por su entrada, soy nuevo en jQuery, pero siempre es bueno tener las cosas son correctas :) Los datos en jqGrid no se rellenan por primera vez, estarán vacíos. Hay un cuadro de entrada de búsqueda para ingresar el número de cliente, después de que el usuario presione el botón "Ir" Estoy haciendo una llamada ajax para completar los datos json en jqgrid, los datos se ven así [{"customerNumber":"64093","customerName":"#9735 WATSONTOWN BILO ","creditCodesPermissions.1":"True","creditCodesPermissions.2":"True","creditCodesPermissions.3":"False","creditCodesPermissions.4":"True","creditCodesPermissions.5":"True","creditCodesPermissions.6":"True","creditCodesPermissions.7":"True","creditCodesPermissions.8":"True","creditCodesPermissions.9":"False","creditCodesPermissions.10":"False","creditCodesPermissions.11":"True","creditCodesPermissions.12":"True","creditCodesPermissions.13":"True","creditCodesPermissions.-1":"True"}], no estoy seguro de cómo usar jsonmap para este tipo de salida, intentaré resolverlo. Voy a probar la opción "celledit" que mencionaste. Gracias por su tiempo y ayuda.

Respuesta

4

No está claro desde el código que ha publicado cómo se completa la cuadrícula. No define ningún datatype, por lo que se usará el valor predeterminado datatype: 'xml' y el jqGrid intentará cargar datos XML por ajax del url que tampoco definió y se usará el predeterminado url: "". Entonces, jqGrid intentará cargar desde su servidor los datos XML. No estoy seguro de que sea querer. Debido a que usa jsonReader, planifica probablemente usar datatype: 'json'. Si incluyera los datos de entrada de prueba en su pregunta, borraría muchas cosas.

El siguiente problema. Utiliza caracteres especiales en la propiedad 'nombre' del colModel ('creditCodesPermissions.7' o incluso 'creditCodesPermissions.-1') que no está permitido. Depende de cómo planeas llenar los datos, puedes usar jsonpmap o xmlmap teniendo los puntos, pero debes hacerlo solo si realmente se requiere y no puedes cambiar el formato de los datos XML/JSON. En cualquier caso, deberá cambiar la propiedad de 'nombre' del colModel por valores como 'creditCodesPermissions7'. No debe usar metacaracteres (como! "# $% & '() * +,./:; < =>? @ [] ^` {|} ~) Como parte literal de un nombre porque los nombres serán utilizados para construir los identificadores de algunos elementos de la red.

Además te recomendaría utilizar column templates. usted sólo debe definir un objeto como

var myCheckBoxTemplate = { 
    width: 40, align: "center", editable: true, edittype: 'checkbox', 
    editoptions: { value: "True:False"}, formatter: "checkbox", 
    formatoptions: {disabled : false} 
}; 

entonces la definición de las columnas en el interior de colModel podría ser como

{name: 'creditCodesPermissions1', index: 'codeOne', template: myCheckBoxTemplate} 

It woul d simplifica tu jqGrid.

Una pequeña observación más: no hay ningún parámetro loadOnce:true. Solo loadonce:true. El parámetro loadOnce:true se ignorará.

Para responder a su pregunta principal, primero es necesario comprender cómo se llenan los datos de la grilla.De cualquier modo, recomendaría que utilizara cualquiera de los tres modos de edición estándar: edición en línea, edición de celda de la edición del formulario. En su caso, la edición en línea o cell editing sería probablemente mejor. En el caso del uso del cell editing, la clase "dirty-cell" se agregará al elemento de celda (elemento <td>) y la clase "edited" se agregará a la fila de cuadrícula (elemento <tr>). De modo que puede usar el hecho para detectar qué celdas cambian las filas del usuario.

+0

Cambié el jcgrid colModel para usar json-map, funcionó bien. – Sri

Cuestiones relacionadas