Example: Formatting Row Data for Display

Custom format row data for display with string templates or custom functions.

Formatting Row Data for Display

Data can be stored in one format but be displayed in a different format. For instance, prices can be stored as numbers but be displayed as "$2.99", and birthdays can be stored as date objects but be displayed as "12/9/2009".

Simple formatting can be defined with a string template on the column definition.

YUI().use("datatable", function(Y) {

    var table = new Y.DataTable({
        columns: [ "id", "name", { key: "price", formatter: "${value}" } ],
        data   : [
            { id: "ga-3475", name: "gadget",   price: 6.99 },
            { id: "sp-9980", name: "sprocket", price: 3.75 },
            { id: "wi-0650", name: "widget",   price: 4.25 }
        ],
        caption: "Data formatting with string template"

    }).render("#template");

When a calculation is needed, define a custom function that generates markup for the data cell. The custom formatter function receives an object with the properties listed in Appendix B in the DataTable user guide.

// See the DataTable user guide for a list of properties on o.
function calculate(o) {
    return "$" + (o.data.price - o.data.cost).toFixed(2);
}

var table = new Y.DataTable({
    columns: [ "id", "name", { key: "profit", formatter: calculate } ],
    data   : [
        { id: "ga-3475", name: "gadget",   price: 6.99, cost: 4.99 },
        { id: "sp-9980", name: "sprocket", price: 3.75, cost: 2.75 },
        { id: "wi-0650", name: "widget",   price: 4.25, cost: 3.25 }
    ],
    caption: "Data formatting with custom function"
}).render("#function");

The DataType utility can be used to help format date objects. This example also uses the emptyCellValue column configuration to supply a custom cell value in the case of missing data.

YUI().use("datatype-date", "datatable", function (Y) {
    function formatDates(o) {
        return o.value &&
            Y.DataType.Date.format(o.value, { format: "%m/%d/%Y" });
    }

    dt = new Y.DataTable({
        columns: [
            "id",
            "name",
            { key: "date", formatter: formatDates, emptyCellValue: "(unknown)" }
        ],
        data   : [
            { id: "ga-3475", name: "gadget",   date: new Date(2006, 5, 1) },
            { id: "sp-9980", name: "sprocket", date: new Date(2004, 8, 16) },
            { id: "wi-0650", name: "widget"} // no date for this record
        ],
        caption: "Data formatting with DataType.Date"
    }).render("#dates");