Search code examples
backbone.jsbackgrid

Backgrid formatter adding values from other columns


Is it possible, with BackGrid, to build a custom Cell vía formatter, composing values from hidden columns?

var grid = new Backgrid.Grid({
  columns: [
   {
   name:"half_value_1",
   cell:"string",
   rendered: false
   },
   {
   name:"half_value_2",
   cell:"string",
   rendered: false
   }, 
   {
    name: "composite",
    cell: "string",
    formatter: _.extend({}, Backgrid.CellFormatter.prototype, {
      fromRaw: function (half_value_1, half_value_2) {
        return half_value_1 + '/' + half_value_2;
      }
    })
  }],
  collection: col
});

Can I get the half_value_1 and half_value_2 inside the fromRaw function?


Solution

  • I think the best way to get the result you want is to use a custom cell rather than a custom formatter. You could do something like this for that particular column:

    {
        name: "composite",
        cell: Backgrid.Cell.extend({
    
            render: function(){
    
                // You have access to the whole model - get values like normal in Backbone
                var half_value_1 = this.model.get("half_value_1");
                var half_value_2 = this.model.get("half_value_2");
    
                // Put what you want inside the cell (Can use .html if HTML formatting is needed)
                this.$el.text( half_value_1 + '/' + half_value_2 );
    
                // MUST do this for the grid to not error out
                return this;
    
            }
    
        })
    }
    

    That should work perfectly for you - I use it for a handful of grids in my projects. I didn't test this code though, so I may have typos :)

    Key