1

I am trying to use a custom formatter for jqgrid in my Ruby on Rails application, but I am having terrible difficulty in getting it to respond.

Here is the function I am using:

function YNFormatter(cellvalue, options, rowObject)
{
     var color = (cellvalue >= 10) ? "green" : "red";

    return '<span style="background-color:' + color + ';">' + cellvalue + '</span>';
}

However, my grid still displays, but without any formatting occurring.

Also, to give context, below is the rest of the jqgrid code for my index.html.erb with the above function included:

<div id="ItmDisplay"></div>

<table id="grid" class="jqInquiryGrid tblGen tblInlineEdit"></table>
<div id="gridPager"></div>


<script>
    $("#grid").jqGrid({
        url:'http://localhost:3000/ItmList',
        datatype: "json",
        altRows:true,
        altclass:'oddRow',

        jsonReader : {
          root:"itmdata",
          page: "currpage",
          total: "totalpages",
          records: "totalrecords",
          cell: "itmrow"
        },

        rowNum:10, 
        rowList:[10,20,30], 
        mtype: "GET",

        width:796,
        hidegrid:false,
        loadonce: true,  

        pager: 'gridPager',

        sortname: 'id', 
        viewrecords: true, 
        sortorder: "asc",

        search: true,

        height: 250,
        width: 600,
        colNames: ['Itm No', 'Title', 'Quantity', 'Category'],
        colModel: [{
            name: 'id',
            index: 'id',
            width: 30,
            sorttype: "int"},
        {
            name: 'title',
            index: 'title',
            width: 90,
            sorttype: "String"},
        {
            name: 'quantity',
            index: 'quantity',
            width: 90,
            sorttype: "float"},
        {
            name: 'category',
            index: 'category',
            width: 80,
            sorttype: "String"}
        ],
        caption: "Items List    ",
        // ondblClickRow: function(rowid,iRow,iCol,e){alert('double clicked');}
    });

function YNFormatter(cellvalue, options, rowObject)
{
    var color = (cellvalue >= 10) ? "green" : "red";

    return '<span style="background-color:' + color + ';">' + cellvalue + '</span>';
 }



    $("#grid").jqGrid('setGridParam', {ondblClickRow: function(rowid,iRow,iCol,e){loadForm(rowid);}});

<script>
// Global variable to hold the record id currently being dealt with 
item_id = 0;

// Function to load the edit form for a given id via AJAX
function loadForm(id) {
    path = "/items/" + id + "/edit"
    item_id = id;
    $("#ItmDisplay").load(path);
}

// function to return the current record id
function get_item_id() {
    return item_id;
}

$(document).delegate('form', 'submit', function(e) {
     e.preventDefault();
      var valuesToSubmit = $(this).serialize();

  // Rails path to pass the update request to    
   updatePath = '/items/' + get_item_id();

$.ajax({
  url: updatePath, //submits it to the given url of the form
  type: "post",
  data: valuesToSubmit,
  dataType: "JSON" 
}).success(function(json){ // the json variable holds the return from the server (JSON Object)
  //act on result.
  $("#ItmDisplay").text("Record Successfully Saved!!").fadeOut(3500);

  var $myGrid = jQuery("#grid");
  data = $myGrid.jqGrid('getGridParam', 'data');
  index = $myGrid.jqGrid('getGridParam', '_index');
  var rowId = json.id, itemIndex = index[rowId], rowItem = data[itemIndex];
  console.log(rowItem);
  rowItem.title = json.title;
  rowItem.quantity = json.quantity;
  rowItem.category = json.category;
  console.log(rowItem);
  $myGrid.jqGrid('setRowData',json.id,rowItem);

});
 });

</script>!

jqrid output

If anyone knows what I am doing wrong, your help would be very gratefully appreciated! Thanks.

NamingError
  • 27
  • 1
  • 5
  • RESOLVED: Hey All, I have got this working now! Came across this approach on StackOverflow which was one I had seen previously while searching the site: http://stackoverflow.com/questions/10653194/jqgrid-set-a-color-conditional-custom-formatter-based-on-row-values Thanks everyone who had a look at the above for me though, very much appreciated, and I hope this solution may help others too :) – NamingError Dec 07 '13 at 12:58

1 Answers1

1

I don't see where you use YNFormatter in your code. You should specify formatter: YNFormatter for some column in colModel.

Another problem is the following: you use background-color CSS style, but there are other CSS styles background which applied from the parent elements. To see the background color one have to remove background-image. So one can fix the problem by usage background-image: none in combination with background-color. It's the main reason of the problem which you described.

The usage of formatter for setting of background color is not the best choice if you use no so old version of jqGrid. It's much better to use cellattr (see my original suggestion to include the feature in jqGrid and the answer for example). The main advantage - you can set background color, but still use predefined formatter like formatter: "date" or formatter: "float".

Some common remarks to the code which you posted:

  • don't use http://localhost:3000 prefix in the URL. Instead of url:'http://localhost:3000/ItmList' it's better to use url:'/ItmList'. It's not only shorter, but it's reduce possibility to make errors because of the same origin restriction of Ajax.
  • you should always add gridview:true option to your grids to improve performance.
  • I recommend to use pager option always in the selector form pager: '#gridPager'. If you use the form pager: 'gridPager' or pager: $('#gridPager') jqGrid will have to "normalize" it and to change the option to pager: '#gridPager'.
  • I recommend to use autoencode: true option if the data returned from the server contains pure data instead of HTML fragments placed in the grid's cells. The option make you sure that all texts returned from the sever will be correctly displayed even the texts contain symbols used for HTML markup.
  • the property sorttype: "String" is unknown (see the documentation). The default value of sorttype property is "text". It's better don't specify any sorttype property if you need the usage of text based sorting.
  • you should remove index properties from colModel items which value are the same as the value of name property. By the way if you use loadonce: true the values of index have to be equal to the value of name property of some columns from colModel. So why to increase the code by including unneeded index properties? The shorter version of colModel seems to me better for reading:
colModel: [
    { name: 'id',       width: 30, sorttype: "int"},
    { name: 'title',    width: 90 },
    { name: 'quantity', width: 90, sorttype: "float" },
    { name: 'category', width: 80 }
]
Community
  • 1
  • 1
Oleg
  • 220,925
  • 34
  • 403
  • 798
  • Brilliant! Thanks a mil Oleg for the all your assistance and for taking the time to write such a detailed response...hugely appreciated!! :) Thanks again! :) – NamingError Dec 07 '13 at 13:58