Dojo – DataGrid – Combining Field values in Formatter

I faced an interesting problem today. I was using a dojo Datagrid and wanted to display a different value in “Author” column if the author value was empty. All the samples I came across on the net were simple formatter examples which dealt with a single column.
Finally I found that the formatter function call has an “undocumented” 2nd argument “rowIndex”. Once I had a handle to this rowIndex, I could retrieve all the fields in the grid row using var rowdata = this.grid.getItem(rowIndex).

var layout = [{
field: “a_content_type”,
name: ‘ ‘,
width: “20px”,
formatter: getIcon
},
{
field: “author”,
name: ‘Author‘,
width: “25%”,
styles: ‘text-decoration:underline;’,
formatter: getAuthor
},……

//You can name the arguments anyway you want.
//You can call this function getAuthor(writer, rowNum), Javascript will pass the values to your arguments when formatter is called.
function getAuthor(author, rowIndex){
if( dojo.string.trim(author) == “”) { //author field was empty so use value from another field
console.debug(“Author was empty = ” + rowIndex);
var rowdata = this.grid.getItem(rowIndex);
return rowdata.owner_name;
} else {
return author;
}
}

9 Responses to Dojo – DataGrid – Combining Field values in Formatter

  1. juanros13 says:

    Thanks helps me a lot

  2. Ron says:

    You sir, are awesome! Thanks.

  3. Thor says:

    THANKS!!

  4. thiswayup says:

    doh! Wish I knew about this a few weeks ago!

  5. multi_io says:

    I was about to also use the rowIndex parameter for this purpose (which *is* documented btw), but people on IRC pointed out that a more elegant way is to define the row’s field name as “_item”, in which case the formatter function will receive the whole item (rowdata) rather than a specific field of it. You can define as many such _item columns as you want, in case you need more than one such column.

    And btw., I think direct field access as in “rowdata.owner_name” is theoretically unsafe because the grid’s store may employ some lazy-loading scheme. You should use store.getValue(rowdata,”owner_name”) instead.

  6. Arcanis says:

    You can use this:
    {
    ‘name’ : ‘BlaBla’,
    ‘width’ : ’24px’,
    ‘fields’ : [ ‘Name’, ‘Surname’, ‘Age’ ],
    ‘formatter’ : this.documentCustomFormatter
    }

    and then in formatter sometnig like this:

    documentNameFormatter : function(fields) {
    return “” + fields[0] + “” + fields[1];
    },

  7. Papa Kosta says:

    Thanx! Where is normal documentation over DataGrid? I need to this rowIndex

  8. It worked fro me after I put the name of the formatter in quotes, such as
    formatter: “getAuthor”

Leave a reply to thiswayup Cancel reply