2011-03-02 17 views
6

Esto es casi la continuación de una pregunta anterior. Problem showing jqgrid with dynamic column bindingCómo agregar formateador personalizado para jqgrid con enlace dinámico de columna

Estoy tratando de poner un formateador personalizado para las columnas como a continuación. Pero nada pasa. Por favor ayuda.

JSP:

<html xmlns="http://www.w3.org/1999/xhtml"> 
    <head> 
    <script type="text/javascript"> 
    $(document).ready(function() { 
    $.ajax({ 
    type : "GET", 
    url : "interFinalTbaAction", 
    data : "", 
    dataType : "json", 
    success : function(result) { 
     var colD = result.couponStripList, colM = result.colModelList; 
     jQuery("#InterFinalTBAGrid").jqGrid({ 
      data : colD.rootVar, 
      datatype : 'local', 
      gridview : true, 
      colModel : colM, 
      loadComplete : function(data) { 
      }, 
      loadError : function(xhr, status, error) { 
       alert('grid loading error'); 
      } 
     }); 
    }, 
    error : function(x, e) { 
     alert(x.readyState + " " + x.status + " " + e.msg); 
    } 
}); 
    }); 
</script> 
</head> 
<body> 
<table id="InterFinalTBAGrid"> 
<tr> 
    <td /> 
</tr> 
</table> 
</body> 
</html> 

El resultado de la acción de JSON:

{ 
"colModelList": [ 
    { 
     "formatter": "CouponFormatter", 
     "index": 0, 
     "jsonmap": null, 
     "key": false, 
     "label": "Coupon", 
     "name": "coupon", 
     "resizable": true, 
     "search": true, 
     "sortable": false, 
     "title": true, 
     "width": 100 
    }, 
    { 
     "formatter": "InterFinalPriceFormatter", 
     "index": 1, 
     "jsonmap": null, 
     "key": false, 
     "label": "03-10-11", 
     "name": "prceCM", 
     "resizable": true, 
     "search": true, 
     "sortable": false, 
     "title": true, 
     "width": 150 
    }, 
    { 
     "formatter": "InterFinalPriceFormatter", 
     "index": 2, 
     "jsonmap": null, 
     "key": false, 
     "label": "04-13-11", 
     "name": "prceCMPlusOne", 
     "resizable": true, 
     "search": true, 
     "sortable": false, 
     "title": true, 
     "width": 150 
    }, 
    { 
     "formatter": "InterFinalPriceFormatter", 
     "index": 3, 
     "jsonmap": null, 
     "key": false, 
     "label": "05-12-11", 
     "name": "prceCMPlusTwo", 
     "resizable": true, 
     "search": true, 
     "sortable": false, 
     "title": true, 
     "width": 150 
    }, 
    { 
     "formatter": "InterFinalPriceFormatter", 
     "index": 4, 
     "jsonmap": null, 
     "key": false, 
     "label": "06-13-11", 
     "name": "prceCMPlusThree", 
     "resizable": true, 
     "search": true, 
     "sortable": false, 
     "title": true, 
     "width": 150 
     } 
    ], 
    "couponStripList": { 
    "rootVar": [ 
     { 
      "coupon": 5.0, 
      "prceCM": "103.734375,103.734375", 
      "prceCMPlusOne": "103.359375,99.03", 
      "prceCMPlusThree": "102.671875,102.671875", 
      "prceCMPlusTwo": "103.015625,103.015625" 
     }, 
     { 
      "coupon": 5.5, 
      "prceCM": "105.984375,105.984375", 
      "prceCMPlusOne": "105.671875,99.2", 
      "prceCMPlusThree": "105.046875,105.046875", 
      "prceCMPlusTwo": "105.359375,105.359375" 
     } 

    ] 
    }, 
    "deliveredDataTimestamp": "03-02-11 11:52:57", 
    "requestedTimestamp": null 
    } 

Las funciones Javascript para formateadores:

function CouponFormatter(cellValue, opts, rowObject) { 
return cellValue + "Testing coupon formatter"; 
    } 

function InterFinalPriceFormatter(cellValue, opts, rowObject) { 
return cellValue + "Testing price formatter"; 
} 

Respuesta

11

Si utiliza

"formatter": "InterFinalPriceFormatter" 

no establece el valor de la propiedad "formateador" en la función .

Una forma de solucionar el problema es recorrer el result.colModelList y verificar que uno use la propiedad "formateador" con algún valor de cadena para el que tenga implementación como la función en el JavaScript. A continuación, puede sobrescribir la propiedad con el valor de la función de formateador correspondiente.

Otra forma será de uso funciones en línea en el formateador:

"formatter": "function (cellValue, opts, rowObject) { return cellValue + \"Testing price formatter\"; }" 

En la forma en que será no tiene una buena separación del código y los parámetros de la red, pero recibe algunos encapsulación del formateador en el interior del cuadrícula.

ACTUALIZADO: espero que el siguiente fragmento de código (no probado) podría dejar claro lo que quiero decir bajo la primera forma de ejecución

var functionsMapping = { 
    // here we define the implementations of the custom formatter which we use 
    "CouponFormatter": function (cellValue, opts, rowObject) { 
     return cellValue + "Testing coupon formatter"; 
    }, 
    "InterFinalPriceFormatter": function (cellValue, opts, rowObject) { 
     return cellValue + "Testing price formatter"; 
    } 
}; 
$.ajax({ 
    type: "POST", 
    url: "interFinalTbaAction.action", 
    data: "", 
    dataType: "json", 
    success: function(result) { 
     var i, cm, colD = result.couponStripList, 
      colN = result.columnNames, 
      colM = result.colModelList; 
     for (i=0;i<colM.length,i++) { 
      cm = colM[i]; 
      if (cm.hasOwnProperty("formatter") && 
       functionsMapping.hasOwnProperty(cm.formatter)) { 
       // fix colM[i].formatter from string to the function 
       cm.formatter = functionsMapping[cm.formatter]; 
      } 
     } 
     jQuery("#dataGrid").jqGrid({/* all parameters from your code */}); 
    },   
    error: function(jqXHR, textStatus, errorThrown){ 
     alert("Error Occured!" + " | " + jqXHR.responseText + " | " + 
       textStatus + " | " + errorThrown); 
    } 
}); 

ACTUALIZACIÓN 2: Sería mejor a registro la formateadores y desentrelazadores personalizados como formateadores estándar como se describe en the old answer o en answer one. Después de eso uno realmente puede usar la sintaxis como "formatter": "InterFinalPriceFormatter" y las funciones definidas personalizadas $.fn.fmatter.InterFinalPriceFormatter y $.fn.fmatter.InterFinalPriceFormatter.unformat serán llamadas automáticamente por jqGrid.

+0

Entendí la parte de la función en línea pero no obtuve la primera parte. Cuando recorro el 'result.colModelList' ¿cómo lo reemplazo con la función de formateador? ¿Puedes poner algún ejemplo de pseudo código, por favor? – silpa

+0

Es algo así como, var InterFinalPriceFormatter = "function (cellValue, opts, rowObject) {return cellValue + \" Testing price formateador \ ";}" – silpa

+0

@silpa: actualizo mi respuesta. La función 'var InterFinalPriceFormatter =" (cellValue, opts, rowObject) {return cellValue + \ "Testing price formateador \";} ";' define la variable 'InterFinalPriceFormatter' que tiene' typeof (InterFinalPriceFormatter) === "string" 'y 'var InterFinalPriceFormatter = function (cellValue, opts, rowObject) {return cellValue + \" Testing price formatter \ "; }; 'define la función y' typeof (InterFinalPriceFormatter) === función "' " – Oleg

Cuestiones relacionadas