The DataTable widget is responsible for rendering columnar data into a highly customizable and fully accessible HTML table. The core functionality of DataTable is to visualize structured data as a table. A variety of Plugins can then be used to add features to the table such as sorting and scrolling.
NOTICE: This component is deprecated and will be removed in future versions. Use the latest supported version of DataTable.
This component will be temporarily supported for implementations that have unresolvable issues preventing them from upgrading to the new APIs. If you find issues while updating to the latest version, please file a ticket.
This module is incompatible with
the new datatable
component
suite. Both use the Y.DataTable
namespace.
Read the Migration Guide for help upgrading from version 3.4.1 or prior.
To include the source files for DataTable (deprecated version) and its dependencies, first load the YUI seed file if you haven't already loaded it.
<script src="http://yui.yahooapis.com/3.8.1/build/yui/yui-min.js"></script>
Next, create a new YUI instance for your application and populate it with the
modules you need by specifying them as arguments to the YUI().use()
method.
YUI will automatically load any dependencies required by the modules you
specify.
<script> // Create a new YUI instance and populate it with the required modules. YUI().use('datatable-deprecated', function (Y) { // DataTable (deprecated version) is available and ready for use. Add implementation // code here. }); </script>
For more information on creating YUI instances and on the
use()
method, see the
documentation for the YUI Global Object.
A basic DataTable is comprised of columns and rows. Define the columns you
want to display in your DataTable with the columnset
attribute. Rows are created for you based on the data you define using the
recordset
attribute. Under the hood, the DataTable class uses
a Columnset instance and a Recordset instance to manage column and row data
properties.
A columnset
can be defined with a simple array of
keys
. As long as these keys exist in your data, DataTable will
display these columns of data in the table. Note that your data may contain
other columns that are not displayed if they are not defined in the
columnset
array. A Columnset will be created containing a
Column instance for each item in your array, with the key
values you provided.
// Creates a Columnset with 3 Columns. "cost" is not rendered. var cols = ["id","name","price"]; // Columns must match data parameter names var data = [ {id:"ga-3475", name:"gadget", price:"$6.99", cost:"$5.99"}, {id:"sp-9980", name:"sprocket", price:"$3.75", cost:"$3.25"}, {id:"wi-0650", name:"widget", price:"$4.25", cost:"$3.75"} ]; // Creates a DataTable with 3 columns and 3 rows var table = new Y.DataTable.Base({ columnset: cols, recordset: data }).render("#example");
For greater flexibility, the columnset
array accepts
configuration objects as well as simple column name strings. When
identifying a column with a configuration object, use the key
property to reference the column name string. Below are a few other
available column configurations.
Use the label
attribute to customize the rendered column
header:
// The label is the text that will be rendered in the table head var cols = [ { key: "id", label: "ID" }, { key: "name", label: "Name" }, { key: "price", label: "Price" } ];
Use the emptyCellValue
attribute to provide custom cell content when
there is no data for that cell in the Recordset
or a formatter
returns
undefined
. The default emptyCellValue
is the empty string ""
.
// The label is the text that will be rendered in the table head var cols = [ { key: "id", label: "ID" }, { key: "name", label: "Name" }, { key: "price", label: "Price", emptyCellValue: "<em>FREE!!!</em>" } ];
Use the abbr
attribute to set the screen-reader friendly
"abbr" on each TH element:
// The abbr attribute enhances the screen-reader experience var cols = [ { key: "mfr-parts-database-id", label: "Mfr Part ID", abbr: "ID" }, { key: "mfr-parts-database-name", label: "Mfr Part Name", abbr: "Name" }, { key: "mfr-parts-database-price", label: "Wholesale Price", abbr: "Price" } ];
Use the children
attribute to created nested column headers.
Parent columns are for display purposes only, not associated with any data,
and should not have a key
attribute of their own.
var nestedCols = [ { label: "Train Schedule", children: [ // Use children to define nested relationships { key: "track" }, { label: "Route", children: [ { key: "from" }, { key: "to" } ] } ] } ]; var data = [ { track: "1", from: "Paris", to: "Amsterdam" }, { track: "2", from: "Paris", to: "London" }, { track: "3", from: "Paris", to: "Zurich" } ]; var table = new Y.DataTable.Base({ columnset: nestedCols, recordset: data, summary: "Train schedule", caption: "Table with nested column headers" }).render("#nested");
Pass an array of data to the recordset
attribute, and
DataTable will create a Recordset
of Record
instances to populate the table. Note that you should only define columns
for data you want to display -- all other data is not displayed.
// Creates a Recordset with 3 records var data = [ { id: "ga-3475", name: "gadget", price: "$6.99", cost: "$5.99"}, { id: "sp-9980", name: "sprocket", price: "$3.75", cost: "$3.25"}, { id: "wi-0650", name: "widget", price: "$4.25", cost: "$3.75"} ]; // Creates a DataTable with 3 columns and 3 rows ("cost" is not displayed) var table = new Y.DataTable.Base({ columnset: [ "id", "name", "price" ], recordset: data }).render("#example");
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.
var cols = [ "id", "name", { key: "price", formatter: "\${value}" } ]; var 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 } ]; var table = new Y.DataTable.Base({ columnset: cols, recordset: data, caption: "Data formatting with string template" }).render("#template");
When a calculation is needed, define a custom function that generates markup for the cell. The custom formatter function receives an object with the following properties:
Property | Value |
---|---|
tbody |
The <tbody> node containing the cell. |
tr |
The <tr> node containing the cell. |
td |
The cell <td> node. As of 3.4.1, this property
is not provided by default, but can be generated by the
createCell
method. |
value |
Usually the value stored in the Record for the column. This is the default content that will be displayed. |
record |
The Record instance containing the data for all cells in the row. |
data |
The raw data collection from the Record instance. |
rowindex |
The row number of the <tr> node containing the cell (zero based). |
column |
The Column instance for the cell's column. |
classnames |
The classname corresponding to the ID of the cell's column. |
headers |
The Array of IDs from all <th> s corresponding to the cell (mostly relevant to nested headers). |
// The custom formatter function recieves an object var calculate = function (o) { var cost = o.record.getValue("cost"), price = o.record.getValue("price"); return "$" + (price - cost).toFixed(2); }; // Assign the custom formatter in the column definition var cols = [ "id", "name", { key: "profit", formatter: calculate } ]; var 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 } ]; var table = new Y.DataTable.Base({ columnset: cols, recordset: data, caption: "Data formatting with custom function" }).render("#function");
Integrate with the DataSource data abstraction utility to easily load data from remote sources and implement features such as caching and polling.
var cols = [ "Title", "Phone", { key: "Rating.AverageRating", label: "Rating" } ]; var myDataSource = new Y.DataSource.Get({ source: "http://query.yahooapis.com/v1/public/yql?&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys" }); myDataSource.plug(Y.Plugin.DataSourceJSONSchema, { schema: { resultListLocator: "query.results.Result", resultFields: [ "Title", "Phone", "Rating.AverageRating" ] } }), var table = new Y.DataTable.Base({ columnset: cols, summary: "Pizza places near 98089" }); table.plug(Y.Plugin.DataTableDataSource, { datasource: myDataSource }) table.render("#pizza"); // Load the data into the table table.datasource.load({ request: "&q=select%20*%20from%20local.search%20where%20zip%3D%2794089%27%20and%20query%3D%27pizza%27" }); // Make another request later table.datasource.load({ request: "&q=select%20*%20from%20local.search%20where%20zip%3D%2794089%27%20and%20query%3D%27chinese%27" });
Enable DataSource caching.
var cols = [ "Title", "Phone", { key: "Rating.AverageRating", label: "Rating" } ]; var myDataSource = new Y.DataSource.Get({ source: "http://query.yahooapis.com/v1/public/yql?format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys" }); myDataSource .plug(Y.Plugin.DataSourceJSONSchema, { schema: { resultListLocator: "query.results.Result", resultFields: ["Title", "Phone", "Rating.AverageRating"] } }) .plug(Y.Plugin.DataSourceCache, { max: 3 }); var table = new Y.DataTable.Base({ columnset: cols, summary: "Pizza places near 98089", caption: "Table with JSON data from YQL" }); table .plug(Y.Plugin.DataTableDataSource, { datasource: myDataSource }) .render("#pizza"); table.datasource.load({ request: "&q=select%20*%20from%20local.search%20where%20zip%3D%2794089%27%20and%20query%3D%27chinese%27" });
Enable DataSource polling.
var cols = ["Title", "Phone", "Rating"]; var myDataSource = new Y.DataSource.IO({ source: "/path/to/service.php?" }); myDataSource.plug(Y.Plugin.DataSourceXMLSchema, { schema: { resultListLocator: "Result", resultFields: [ { key: "Title", locator: "*[local-name() ='Title']" }, { key: "Phone", locator: "*[local-name() ='Phone']" }, { key: "Rating", locator: "*[local-name()='Rating']/*[local-name()='AverageRating']" } ] } }); var table = new Y.DataTable.Base({ columnset: cols, summary: "Chinese restaurants near 98089", caption: "Table with XML data from same-domain script" }); table .plug(Y.Plugin.DataTableDataSource, { datasource: myDataSource, initialRequest: "zip=94089&query=chinese" }) .render("#chinese"); myDataSource.setInterval(5000, { request: "zip=94089&query=chinese", callback: { success: Y.bind(table.datasource.onDataReturnInitializeTable, table.datasource), failure: Y.bind(table.datasource.onDataReturnInitializeTable, table.datasource) } });
Column sorting functionality for the deprecated version of DataTable can be
added with the DataTableSort plugin (provided by the
datatable-sort-deprecated
module, or in the
datatable-deprecated
rollup module). Indicate which columns
are sortable by setting sortable: true
in your column
definitions.
var cols = [ { key: "Company", sortable: true }, { key: "Phone" }, { key: "Contact", sortable: true } ]; var data = [ { Company: "Company Bee", Phone: "415-555-1234", Contact: "Sally Spencer"}, { Company: "Acme Company", Phone: "650-555-4444", Contact: "John Jones"}, { Company: "Indutrial Industries", Phone: "408-555-5678", Contact: "Robin Smith"} ]; var table = new Y.DataTable.Base({ columnset: cols, recordset: data, summary: "Contacts list", caption: "Table with simple column sorting", plugins: [ Y.Plugin.DataTableSort ] }).render("#sort");
Note: Scrolling is not currently supported on the Android WebKit browser.
Scrolling functionality for the deprecated version of DataTable can be added with the DataTableScroll plugin (provided by the datatable-scroll-deprecated
module or in the datatable-deprecated
rollup module). Horizontal scrolling is enabled by setting a width
attribute value; fixed header vertical scrolling is enabled by setting a height
attribute value; and xy-scrolling is enabled by setting both width
and height
values.
var cols = [ { key: "Company" }, { key: "Phone" }, { key: "Contact" } ]; var data = [ { Company: "Company Bee", Phone: "415-555-1234", Contact: "Sally Spencer"}, { Company: "Acme Company", Phone: "650-555-4444", Contact: "John Jones"}, { Company: "Indutrial Industries", Phone: "408-555-5678", Contact: "Robin Smith"} ]; var table = new Y.DataTable.Base({ columnset: cols, recordset: data, }); table .plug(Y.Plugin.DataTableScroll, { width: "300px", height: "200px" }) .render("#scroll");