yuiyui3

How can I dynamically add rows and columns to a YUI dataTable


I am trying to modify the the YUI sortable dataTable example to add rows and columns dynamically after the dataTable is created. My code looks like this:

YUI().use("datatable-sort", function(Y) {
    var cols = [
        {key:"Company", label:"Click to Sort Column A", sortable:true},
        {key:"Phone", label:"Not Sortable Column B"},
        {key:"Contact", label:"Click to Sort Column C", sortable:true}
    ],
    data = [
        {Company:"Company Bee", Phone:"415-555-1234", Contact:"Sally Spencer"},
        {Company:"Acme Company", Phone:"650-555-4444", Contact:"John Jones"},
        {Company:"Industrial Industries", Phone:"408-555-5678", Contact:"Robin Smith"}
    ],
    table = new Y.DataTable({
        columns: cols,
        data   : data,
        summary: "Contacts list",
        caption: "Table with simple column sorting"
    }).render("#sort");

    // Add rows and columns here.
});

Solution

  • You can dynamically add rows into a YUI dataTable by calling the addRow() or addRows() method. If you are using the YUI sortable dataTable example, you could do it this way:

    table.addRows(
        [{Company:"New Company", Phone:"555-555-5555", Contact:"John Smith"},
        {Company:"Old Company", Phone:"555-555-6666", Contact:"Rowdy Piper"}]);
    

    Dynamically loading columns can be done similarly with addColumn():

     table.addColumn({key:"NewColumn", label:"Column D"});
    

    Note: you must include the datatable-mutable module in your code to utilize these methods.