Developer Network Home - Help

Yahoo! UI Library: DataTable

DataTable

The DataTable Control interface with the default YUI Sam Skin applied.The DataTable control provides a simple yet powerful API to display screen-reader accessible tabular data on a web page. Notable features include sortable columns, pagination, scrolling, row selection, resizeable columns, and inline editing.

Note: The DataTable control is being released as a beta component. Please refer to the FAQ for what we mean by this designation. We look forward to your feedback in the YUI Forums.

The 2.5.1 beta release of DataTable presents significant API changes from the 2.4.1 beta release. While every effort has been made to maintaining backward compatibility, implementers who are upgrading from a previous version are strongly advised to review the Upgrade Notes below, the Release Notes, and the API reference.

YUI community member Daniel Barreiro (screen name Satyam) has contributed two terrific articles on the YUI DataTable Control on YUIBlog (Part One: Getting Started; Part Two: Changing Data in the DataTable). In addition to reading this User's Guide by DataTable author Jenny Han Donnelly, we strongly recommend that you review Satyam's work in preparing for your DataTable implementation.

Upgrade Notes

Overview

Users new to DataTable can skip this section and proceed directly to the Getting Started section. Implementers who are upgrading from previous versions of DataTable should note that the 2.5.1 release of DataTable introduces significant changes to the underlying architecture of the widget, including

  • considerable changes to generated markup,
  • improvements to performance via a new rendering scheme,
  • stabilization of the fixed-header vertical scrolling feature,
  • built-in support for horizontal scrolling,
  • the introduction of a versatile Paginator class,
  • more consistent and robust integration with the DataSource utility,
  • bug fixes and code refactoring to make customizations to inline editing and the selection model easier,
  • and the introduction of Column show/hide/remove/insert APIs and DragDrop integration with Column reordering.

The following important changes have also been made to the DataSource Utility:

  • usage of a callback object literal rather than a callback function and caller reference,
  • access to the entire data response after it as been type-converted but before it has been schema-parsed,
  • consistency to the oParsedResponse object's members returned by the DataSource to the callback.

Please read the DataSource Upgrade Notes section for further details.

While much care has been taken to support backward compatibility whenever possible, implementers are advised to read through this user guide carefully, and upgrade their implementation code at their earliest convenience.

Markup Changes

The underlying DOM structure of the DataTable has been dramatically revamped in order to better support dynamic column resizing and xy-scrolling, all while maintaining screenreader accessibility. Please refer to the Object Model Overview diagram in the Getting Started section for details on the markup that is generated.

Fixed headers for scrolling tables

The more substantial change is for the creation of fixed headers for xy-scrolling tables. When you enable the scrollable configuration for your DataTable, a separate <table> element is used to display the column headers, allowing the rows of data to be scrolled independently.

Cell liners for dynamic column widths

Each <th> and <td> element now contains a liner <div> to prevent browsers from limiting column widths to the width of the column's widest content.

API changes

As a result of these changes to the generated markup, the following APIs were completely removed:

  • CLASS_SCROLLBODY
  • CLASS_TABLE
  • getTableEl()

The following APIs were added:

  • YAHOO.widget.DataTable.CLASS_LINER
  • getContainerEl()
  • getTheadEl()
  • getTbodyEl()
  • getThLinerEl()
  • getTdLinerEl()

And the following API signatures were changed:

  • formatCell(elCell, oRecord, oColumn) - The first argument elCell is now a reference to the <div> liner element rather than the <td> itself.

In an effort to disambiguate DOM elements from JavaScript objects, the following APIs have been renamed:

  • headerCellClickEvent - Use theadCellClickEvent.
  • headerCellDblclickEvent - Use theadCellDblclickEvent.
  • headerCellMousedownEvent - Use theadCellMousedownEvent.
  • headerCellMouseoutEvent - Use theadCellMouseoutEvent.
  • headerCellMouseoverEvent - Use theadCellMouseoverEvent.
  • headerLabelClickEvent - Use theadLabelClickEvent.
  • headerLabelDblclickEvent - Use theadLabelDblclickEvent.
  • headerLabelMousedownEvent - Use theadLabelMousedownEvent.
  • headerLabelMouseoutEvent - Use theadLabelMouseoutEvent.
  • headerLabelMouseoverEvent - Use theadLabelMouseoverEvent.
  • headerRowClickEvent - Use theadRowClickEvent.
  • headerRowDblclickEvent - Use theadRowDblclickEvent.
  • headerRowMousedownEvent - Use theadRowMousedownEvent.
  • headerRowMouseoutEvent - Use theadRowMouseoutEvent.
  • headerRowMouseoverEvent - Use theadRowMouseoverEvent.

New Progressive Rendering Scheme

In order to improve performance, a new rendering scheme has been implemented that can use a timeout queue to draw DOM elements without blocking the browser's UI thread. You can activate progressive rendering of your records via the renderLoopSize configuration.

To account for this change, the following APIs have been deprecated:

  • refreshView() - Use render().
  • refreshEvent - Use renderEvent.

New Scrolling Architecture

DataTable now supports three types of scrolling:

  • x-scrolling: horizontal scrolling where Column headers track with the body
  • y-scrolling: vertical scrolling where Column headers are fixed while the body scrolls
  • xy-scrolling: combined horizontal and vertical scrolling where Column headers are fixed vertically but track horizontally

Implementers who were previously using CSS to achieve scrolling are now required to remove those styles and set heights and widths via DataTable constructor configs as described in the Scrolling section below.

New Paginator Class

We are pleased to introduce the new Paginator class to manage and render pagination states for the DataTable widget. The value for the config paginator should now be an instance of YAHOO.widget.Paginator rather than an object literal of values. As a result of the new pagination model, the following APIs have been deprecated:

  • formatPaginatorDropdown() - Use new Paginator class.
  • formatPaginatorLinks() - Use new Paginator class.
  • formatPaginators() - Use new Paginator class.
  • updatePaginator() - Use new Paginator class.
  • paginated - No longer used.

Please refer to the Pagination section below for implementation details.

DataSource Integration Changes

For more detail on changes to the DataSource API, please refer to the DataSource Upgrade Notes section.

As a result of the change to the DataSource's callback value, the following DataTable APIs have been changed:

  • doBeforeLoadData(sRequest, oResponse, oPayload)
    onDataReturnAppendRows(sRequest, oResponse, oPayload)
    onDataReturnInitializeTable(sRequest, oResponse, oPayload)
    onDataReturnInsertRows(sRequest, oResponse, oPayload)
    - In each of these methods, oPayload is now an optional data payload the implementer can pass in to DataSource.sendRequest() via the callback object literal's argument member.

As a result of DataSource's new access to the oFullResponse object, the following APIs have been changed in the DataTable class:

  • doBeforeLoadData(sRequest, oResponse, oPayload)
    onDataReturnAppendRows(sRequest, oResponse, oPayload)
    onDataReturnInitializeTable(sRequest, oResponse, oPayload)
    onDataReturnInsertRows(sRequest, oResponse, oPayload)
    - oResponse is now the full response typed appropriately to JSON, XML, etc. Implementers no longer need to convert this data.

With the introduction of the metaFields collection in the DataSource responseSchema, the DataTable supports some "magic" meta fields, usable to control pagination and sorting states. See the DataSource magic meta section for more details.

Other API Changes

DataTable Class

  • sortedBy.dir - When setting the sorted state on your DataTable, use the class constants YAHOO.widget.DataTable.CLASS_ASC or YAHOO.widget.DataTable.CLASS_DESC instead of the strings "asc" and "desc".

RecordSet Class

  • updateKey() - Use updateRecordValue().
  • keyUpdateEvent - Use recordValueUpdateEvent.

Column Class

  • sortOptions.defaultOrder - When setting the default sort direction on a Column, use the property sortOptions.defaultDir, instead of sortOptions.defaultOrder, and use class constants YAHOO.widget.DataTable.CLASS_ASC or YAHOO.widget.DataTable.CLASS_DESC instead of the strings "asc" and "desc".

Getting Started

To use the DataTable control, include the following source files in your web page. Please note that the Element utility is a new dependency as of the 2.3.0 release.

YUI dependency configurator.

YUI Dependency Configurator:

Instead of copying and pasting the filepaths above, try letting the YUI dependency Configurator determine the optimal file list for your desired components; the Configurator uses YUI Loader write out the full HTML for including the precise files you need for your implementation.

Note: If you wish to include this component via the YUI Loader, its module name is datatable. (Click here for the full list of module names for YUI Loader.)

Where these files come from: The files included using the text above will be served from Yahoo! servers; see "Serving YUI Files from Yahoo!" for important information about this service. JavaScript files are minified, meaning that comments and white space have been removed to make them more efficient to download. To use the full, commented versions or the -debug versions of YUI JavaScript files, please download the library distribution and host the files on your own server.

Order matters: As is the case generally with JavaScript and CSS, order matters; these files should be included in the order specified above. If you include files in the wrong order, errors may result.

Using "CSS skins": One of the files listed above contains a CSS "skin" for the DataTable Control. For this skin CSS to work correctly, you will need to apply the CSS class "yui-skin-sam" to an element that is a parent of the element in which the component lives. You can usually accomplish this simply by putting the class on the <body> tag:

<body class="yui-skin-sam">

For more information on skinning YUI components and making use of default skins, see our Understanding YUI Skins article here on the website.

Object Model Overview

DataTable creates an internal ColumnSet object to define the header cells for the <thead> and an internal RecordSet object to locally hold data for the rows of the table. The ColumnSet is created using the Column definitions passed in via the constructor, and the RecordSet is created using the ColumnSet object and populated with data provided by the DataSource.

The markup for a DataTable instance starts with the implementer-defined outer container, into which two <table> elements are created. Each <table> is housed in its own container, identified as either the "header container" or the "body container".

The <table> in the header container consists only of a single <thead> element of Column header <th>s. The <table> in the body container consists of a similar <thead> as well as a primary <tbody> element to display cells of data and a secondary <tbody> element to display stateful messages such as "Loading data..." or "No data found".

When the scrollable configuration is set to true, the header container table is displayed and the body container's thead is hidden (but accessible to screen readers). Otherwise, the header container is hidden.

The following diagram describes the DOM elements that are generated in the outer container. Note that the assigned CSS class names should be used as hooks to skin or customize the UI.

Overview of generated markup

Defining Column Headers

After the container element, the next argument in the DataTable constructor is an array of Column definitions that represent each <th> element that will adorn the top of your DataTable. In the simple example below, each Column object literal maps to a data field we will define in the DataSource (see "Instantiating a DataSource" below) and uses the following properties:

  • The key is the name assigned to each Column. Columns with keys that map to a data field will automatically populate with that data. Columns with unknown keys will require you to populate the field manually, through the use of a custom formatter. If a key is not defined here, one will be auto-generated.
  • The label is the string or HTML value displayed in each <th> element. If the label is null or undefined, the Column header will display the key value as a default.

The following Column properties are also supported:

  • abbr
  • children
  • className
  • editor
  • editorOptions
  • formatter
  • minWidth (default value is 10)
  • resizeable (requires the Drag & Drop Utility)
  • sortable
  • sortOptions
  • width (must be a Number)

Note that you may define more Columns than fields and use a custom formatter to populate these cells with data from the RecordSet or any other custom value.

Supplying a custom class name via the className property will assign that value to all cell liners of that Column. Additionally, the Column's key is used to assign a generated class name for all liners of a Column:

"yui-dt-col-" + key

Note that any special characters other than "A-Z", "a-z", "0-9", "_", "-", ".", or ":" will get stripped from this generated class name. Please refer to the Object Model Overview diagram in the Getting Started Section for details on other class names that are applied by the DataTable widget.

Instantiating a DataSource

The last argument for your DataTable constructor is a DataSource instance that defines where the data for the DataTable lives. In this example, the data for this DataTable lives in a local JavaScript array assigned to the variable YAHOO.example.puppies:

To create a DataSource, pass the array to the DataSource constructor. Then set the responseType to the class constant YAHOO.util.DataSource.TYPE_JSARRAY, and set which fields the DataTable will use -- these fields should map to the Column keys that you defined earlier.

Defining a field in your DataSource causes that data to get copied from the original array into the DataTable's local RecordSet. In the simple case, fields will correlate one-to-one to Columns in your DataTable, but note that you may have fields that are not meant for display to the user. Every field you define in your DataSource will be available in the DataTable's RecordSet, regardless of whether or not they are actually displayed in the UI. To withhold data from the UI, be sure not to define a Column for that field.

Supported responseType values are:

  • YAHOO.util.DataSource.TYPE_JSARRAY
  • YAHOO.util.DataSource.TYPE_JSON
  • YAHOO.util.DataSource.TYPE_HTMLTABLE
  • YAHOO.util.DataSource.TYPE_XML
  • YAHOO.util.DataSource.TYPE_TEXT

Instantiating a DataTable

Now you are ready to instantiate your DataTable by passing in

  1. the ID string or element reference of a container DIV element;
  2. your Column definitions; and
  3. your DataSource instance.

Make sure the container element is available in the DOM before instantiating your DataTable, either by placing your script in the HTML body after the markup has been rendered, waiting until the window load DOM event fires, or by using the Event Utility's onAvailable method to programmatically create your DataTable as soon as the container element is available.

Understanding Records, Rows, and DOM Elements

A DataTable instance is made up of a Columnset, a Recordset, and DOM elements:

  • ColumnSet The ColumnSet is a set of Column instances. Each Column represents a field of data. Each Column is assigned a unique key index, which represents its order within the ColumnSet. Each Column is also assigned an ID, which is globally unique across all ColumnSets and has no bearing on display order.
  • RecordSet The RecordSet is a set of Record instances. Each Record represents a row of data. Each Record is assigned a globally unique ID, which remains constant regardless of sort order. Each Record is also assigned a RecordSet index which represents its current sort order index within the RecordSet.
  • DOM elements In the DOM, a <table> element contains a collection of <tr> elements. Each <tr> element displays a Record of data. If the DataTable is paginated, then the <table> will show only a subset of the entire RecordSet. Although each <tr> is assigned a Record instance to display, its unique DOM ID has no relation to its Record's Record ID or RecordSet index. Each <tr> is assigned a yuiRecordId expando property which associates it to its Record. Please note that the DOM ID and yuiRecordId are not related: Sorting will cause yuiRecordId values to be reassigned to <tr> elements but DOM IDs will *not* be reassigned .

The DataTable class provides a set of methods to interact with the DOM elements and their underlying data, such as addRow(), updateRow(), and deleteRow(). Calling addRow(oData) on the DataTable will create a Record of data at the end of the RecordSet, and create and populate a new <tr> element at the bottom of the <table> element. Calling addRow(oData, i) will create a new Record of data and a new <tr> element and insert them into the given index position i of the RecordSet and <table>, respectively.

In cases where pagination is enabled on the DataTable, calling addRow() will always add a Record to the RecordSet, but will only add a <tr> element to the <table> if the new Record is in view within the current page. Implementers should keep this in mind when dealing with RecordSet index values, as these values may or may not be equal to <tr> index values if pagination is enabled.

Using DataTable

The DataTable class and its related classes provides many configuration parameters for you to fine-tune the user experience of your DataTable instance.

Progressive Enhancement of Markup

By progressively enhancing <table> markup that is already on the page, you can make core content available to end users who do not have JavaScript enabled, while delivering a fully functional DataTable control to users who do have JavaScript enabled -- all from the same code base.

To this end, the DataSource accepts an HTML <table> element as a source of data. The DataTable will parse the data out of the table, remove it from the DOM, and replace it with an enhanced control.

Accessibility Features

Out of the box, the DataTable is accessible via screen readers and keyboard-navigable. Please take advantage of the following additional features to further enhance accessibility:

Custom Cell Formatting

The DataSource class provides a set of built-in static functions to format certain well-known types of data. In your Column definition, if you set a Column's formatter to YAHOO.widget.DataTable.formatDate, that function will render data of type Date with the default syntax of "MM/DD/YYYY". If you would like to bypass a built-in formatter in favor of your own, you can point a Column's formatter to a custom function that you define.

As of the 2.3.0 release, the static formatter functions are called within the scope of the DataTable instance. Also as a convenience, the following string shortcuts may be used to point to the built-in formatter functions:

  • "button" points to YAHOO.widget.DataTable.formatButton
  • "checkbox" points to YAHOO.widget.DataTable.formatCheckbox
  • "currency" points to YAHOO.widget.DataTable.formatCurrency
  • "date" points to YAHOO.widget.DataTable.formatDate
  • "dropdown" points to YAHOO.widget.DataTable.formatDropdown
  • "email" points to YAHOO.widget.DataTable.formatEmail
  • "link" points to YAHOO.widget.DataTable.formatLink
  • "number" points to YAHOO.widget.DataTable.formatNumber
  • "radio" points to YAHOO.widget.DataTable.formatRadio
  • "text" points to YAHOO.widget.DataTable.formatText
  • "textarea" points to YAHOO.widget.DataTable.formatTextarea
  • "textbox" points to YAHOO.widget.DataTable.formatTextbox

Nested Column Headers

If you'd like your DataTable to display nested headers, the control will automatically correlate the correct set of headers to each <td,> element in order to support screen reader accessibility. In your Column definitions, any given Column object literal can itself host an array of Column object literals. Use the children property to assign descendant Columns. The following Column properties will cascade to descendant Columns if they are defined by a parent but not defined explicitly by children.

  • className
  • editor
  • editorOptions
  • formatter
  • resizeable
  • sortable
  • width

Basic Column Sorting

By default, if a Column is defined with sortable:true, then clicking on the Column header will execute a basic sort function that supports comparisons of Strings, Numbers, and Dates.

Keep in mind that sorting a Column first sorts the data in the underlying RecordSet and then updates the DOM UI to reflect this new sort order. Therefore, the type of the data (e.g., String, Number, Date, etc.) held in the RecordSet determines the sort algorithm, not the type as defined in your Column definition formatter property.

In general, the RecordSet expects to hold data in native JavaScript types. For instance, a date is expected to be a JavaScript Date instance, not a string like "4/26/2005" in order to sort properly. Converting data types as data comes into your RecordSet is enabled through the parser property in the fields array of your DataSource's responseSchema. This is especially useful when data is coming over XHR as a String and needs to be converted to a Number, Boolean, Date, etc. A custom function can be defined, or you can use one of the static built-in functions:

If your initial data is already sorted, be sure to specify the DataTable config property sortedBy to display the proper UI at instantiation. The value of the property should be either the class constant YAHOO.widget.DataTable.CLASS_ASC or YAHOO.widget.DataTable.CLASS_DESC. Now when the user goes to sort this Column, DataTable will know to sort it in the correct (opposite) direction. Note that setting the sortedBy property does not perform a sort on the Column, it merely applies the appropriate CSS when the DataTable loads.

Advanced Column Sorting

The sortOptions property can be used in your Column definitions to specify more advanced sort options. If a Column's default sort direction should be in descending order rather than ascending order, as is often the case for reverse-chronological date fields, be sure to define the defaultDir property on sortOptions:

More complex data structures may require custom sort algorithms. You can provide custom sort functions in your Column definition via the sortOptions property. The code below is an example of how to implement nested sorting, where clicking on Column2's header will sort by values in Column2 and, if there are equal values, further sort by values in Column1.

Please note that as of the 2.3.0 release, a single sort function is used for both ascending and descending sorts.

Pagination

Pagination can be used to reduce the real-estate footprint of DataTables with large data sets. As of the 2.5.0 release, implementors should use the new Paginator class to define pagination layout and behavior for the DataTable.

By default, the DataTable will render a set of pagination controls above and below the table:

rendered pagination controls

Templates and UI components

The Paginator class uses a template and component architecture to afford the greatest flexibility in choosing how to render the pagination controls.

This Paginator configuration would result in the following UI:

rendered pagination controls with a custom template

Paginator instances use the configuration attribute template to describe the markup for rendering the pagination controls. The template string contains placeholders to identify where the various control elements should be located. Each placeholder in the template is the class name of a UI component found in the YAHOO.widget.Paginator.ui namespace.

The default template is "{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}".

The following UI components are provided in the 2.5.1 release:

  • FirstPageLink
  • PreviousPageLink
  • NextPageLink
  • LastPageLink
  • PageLinks
  • RowsPerPageDropdown
  • CurrentPageReport

For custom pagination controls, create new UI component classes in the YAHOO.widget.Paginator.ui namespace and reference them in your Paginator template.

See the API docs for Paginator and each UI component class for available configuration.

Scrolling

Scrolling is another way to conserve the UI footprint of larger data sets. In the DataTable control, scrolling can be

  • x-scrolling: horizontal scrolling where Column headers track with body
  • y-scrolling: vertical scrolling where Column headers are fixed while body scrolls
  • xy-scrolling: combined horizontal and vertical scrolling where Column headers are fixed vertically but track horizontally

To enable scrolling, set {scrollable:true} in the DataTable constructor config, and define width and/or height String values. X-scrolling is enabled by only setting a width, y-scrolling is enabled by only setting a height, and xy-scrolling is enabled by setting both:

Adjusting the Render Loop Size

In cases where your DataTable needs to display the entirety of a very large set of data, the renderLoopSize config can help manage browser DOM rendering so that the UI thread does not get locked up on very large tables. Any value greater than 0 will cause the DOM rendering to be executed in setTimeout() chains that render the specified number of rows in each loop. By default, all rows will be rendered in a single loop.

Row and Cell Selection Modes

You can enable row selection or cell selection by assigning the built-in onEventSelectRow event handler to a Custom Event.

The property selectionMode is used to enable or disable modifier keys and define the multi-selection paradigm. By default, selectionMode is set to standard which enables the modifier keys <shift> and <ctrl> to select multiple rows.

Setting selectionMode to single enables row selection but disables the use of modifier keys for multi-selection.

Setting selectionMode to cellblock, cellrange, or singlecell enables cell selection in block mode, range mode, or single mode respectively.

Take care that the selectionMode value matches the mode you have enabled. If you have assigned the onEventSelectCell handler, then selectionMode needs to be set to "cellblock", "cellrange", or "singlecell" exclusively. Conversely, the values "standard" and "single" are reserved for DataTables with row selection enabled. Finally, mixing and matching row and cell selection paradigms is not recommended.

The methods selectRow() and selectCell() also allow you trigger selection programmatically:

The following methods allow you to retrieve selected rows and cells as an array:

The look and feel of a selected element can be customized via CSS:

Column Selection

You can enable Column selection by assigning the built-in onEventSelectColumn event handler to a Custom Event.

The methods selectRow() and selectCell() also allow you trigger selection programmatically:

The following methods allow you to retrieve selected Columns as an array:

The look and feel of a selected element can be customized via CSS:

Cell, Row, and Column Highlighting

You can enable cell, row or Column highlighting by assigning the appropriate built-in event handlers to Custom Events. Please note that mixing and matching cell, row and Column highlighting is not recommended.

The look and feel of a highlighted element can be customized via CSS:

More Column APIs

Columns may be hidden, shown, inserted, or deleted. At this time, these APIs are only supported for Columns which are not nested children of other Columns. The methods hideColumn() and showColumn() merely adjust the width values in the UI. However, removeColumn() and insertColumn() will remove and insert Column instances from the actual ColumnSet.

If the Drag & Drop Utility is available on the page, Column reordering can be enabled in your DataTable constructor:

Inline Cell Editing

Inline cell editing can be enabled by assigning the built-in onEventShowCellEditor event handler to a Custom Event. Define the editor type with the editor property in your Column definition. As a convenience, the following string shortcuts may be used to point to the built-in editor functions, but a custom editor function may also be defined:

  • "checkbox" points to YAHOO.widget.DataTable.editCheckbox
  • "date" points to YAHOO.widget.DataTable.editDate
  • "dropdown" points to YAHOO.widget.DataTable.editDropdown
  • "radio" points to YAHOO.widget.DataTable.editRadio
  • "textarea" points to YAHOO.widget.DataTable.editTextarea
  • "textbox" points to YAHOO.widget.DataTable.editTextbox

Defining Custom Event Handlers

The DataTable control provides a robust Custom Event model to allow you to seamlessly integrate and expand upon its built-in fuctionality. For example, after you enable inline cell editing (see Inline Cell Editing), you may want to provide a confirmation to your users in reaction to a successful edit event. Note that the newData value passed to your handler function is the value of the form input field, so in the case of a textbox editor, even if the user has entered a number, the type of the input value will be String.

Please refer to the API documentation for a full list of Custom Events that are available for the DataTable control.

Working with DataSources

Initial Data

By default, DataTable will fire off a request for data to the DataSource at instantiation. You can disable this feature by setting the config initialLoad to false in the constructor:

If, however, you would like to customize the request sent to the DataSource in the initial load, you can set that value via the initialRequest config:

You can further customize the intitial request that is sent to the DataSource by setting the initialLoad config to be an object literal. Doing so allows you to pass in an arbitrary payload of data that will be accessible to you in the callback loop:

Getting More Data

Data can always retrieved with a sendRequest() call to the DataSource, by passing in a DataTable method as a callback handler.

XHR DataSources

If your data is not held in local memory as a JavaScript value, you can point your DataSource instance to a server-generated response and access the data over XHR. Due to browser security constraints, you'll need either a local server URL or a local proxy to a remote host. The DataSource utility supports XHR response types that are JSON, XML, and plain text (such as comma-delimited strings). If your data return as JSON, be sure to include the JSON Utility on your page as a dependency.

Please note that as of the 2.3.0 release, DataSource requests over XHR no longer automatically insert a "?" in the URIs between the host and the query. Implementers should explicitly include the question mark if it is required by your server.

JSON Data

If the data for your DataTable is held in JSON, it may look something like this:

You'll want to configure your DataSource like this:

Note: The value for resultsList should be of type String. Values of type Array are not acceptable.

XML Data

If the data for your DataTable is held in XML, it may look something like this:

You'll want to configure your DataSource like this:

Plain Text Data

If the data for your DataTable is sent as plain text, it may look something like this:

You'll want to configure your DataSource like this:

DataSource magic meta

As of 2.5.1, DataSources can be configured to extract arbitrary data from JSON or XML responses using the responseSchema.metaFields collection. Values discovered in the oFullResponse at the metaFields locations will be added to the oParsedResponse.meta object which is then passed on to the DataTable. The DataTable will then look for a few "magic" meta fields in the response object, combine them with special fields in the oPayload object, then use the aggregated information to update its pagination and sorting states. DataTable's onDataReturn methods look for the following magic meta:

recordInsertIndex
Used by onDataReturnInsertRows to indicate the RecordSet index to insert the results at. Defaults to 0.
recordStartIndex
Used by onDataReturnSetRows to indicate the first RecordSet index to set. Defaults to the Paginator's current record offset if the table is paginated; otherwise 0.
sortKey
Used with sortDir to update the DataTable's sortedBy attribute.
sortDir
Used with sortKey to update the DataTable's sortedBy attribute.
paginationRecordOffset
Used to update the Paginator to indicate which page is being displayed.
paginationRowsPerPage
Used to update the Paginator to calculate how to divide the records into discrete pages.
totalRecords
Used to update the Paginator to calculate how many pages of data to provide access to.

Magic meta are useful when you either have control of the format of the JSON/XML service response you are consuming or at least know that it includes needed information. For cases where you do not have control and the service does not provide all the information you need, you can leverage the sendRequest callback object's argument member, which the DataSource will pass to the DataTable's onDataReturn callback as the third parameter, oPayload.

Server-side Sorting and Pagination

If you need your remote server to handle sorting and/or pagination algorithms, you should provide custom code in the following manner:

Skinning DataTable

DataTable comes with a default presentation or "skin," part of the "Sam Skin" visual treatment that accompanies most YUI controls. You can read more about the general approach to skinning YUI components in this in-depth article.

The CSS provided with DataTable is comprised of core, functional CSS as well as the Sam Skin visual treatment.

The DataTable Control

To explore the CSS which controls the DataTable's presentation, please review the DataTable Skinning Example where the full CSS for the control is displayed.

Top Known Issues

Please see the bug repository at SourceForge for a complete list of known issues.

DataTable Nested in a TD Element Hangs IE7

Implementers creating a scrollable DataTable nested within another table should include the following patch to avoid problems in IE7:

Wide Content Truncation in Gecko Browsers

Gecko browsers may truncate some content of Columns whose widths are not specified if a table's overall content is wider than the viewport or its parent container.

IE Quirks Mode Column Widths

In IE quirks mode, Columns without specified widths are not always auto-sized correctly.

In IE Borders Remain Visible When DataTable or Parent Is Hidden

Due to an IE bug, any TABLE element with its border-collapse CSS property set to "collapse", will keep its borders visible even while its contents will be hidden correctly.

Table Captions Incompatible with Column Resizing in Opera

In Opera, table captions interfere with the positioning algorithms needed for Column resizing.

Opera Column Inconsistencies With "scrollable" Enabled

In Opera, scrollable DataTables may experience truncated Column content when widths are not specified in the definition.

Arrow Selection Not Supported in Safari

Due to a known limitation in Safari, arrow selection of rows and/or cells is not supported at this time.

YUI on Mobile: Using DataTable Control with "A-Grade" Mobile Browsers

About this Section: YUI generally works well with mobile browsers that are based on A-Grade browser foundations. For example, Nokia's N-series phones, including the N95, use a browser based on Webkit — the same foundation shared by Apple's Safari browser, which is found on the iPhone. The fundamental challenges in developing for this emerging class of full, A-Grade-derived browsers on handheld devices are:

  • Screen size: You have a much smaller canvas;
  • Input devices: Mobile devices generally do not have mouse input, and therefore are missing some or all mouse events (like mouseover);
  • Processor power: Mobile devices have slower processors that can more easily be saturated by JavaScript and DOM interactions — and processor usage affects things like battery life in ways that don't have analogues in desktop browsers;
  • Latency: Most mobile devices have a much higher latency on the network than do terrestrially networked PCs; this can make pages with many script, css or other types of external files load much more slowly.

There are other considerations, many of them device/browser specific (for example, current versions of the iPhone's Safari browser do not support Flash). The goal of these sections on YUI User's Guides is to provide you some preliminary insights about how specific components perform on this emerging class of mobile devices. Although we have not done exhaustive testing, and although these browsers are revving quickly and present a moving target, our goal is to provide some early, provisional advice to help you get started as you contemplate how your YUI-based application will render in the mobile world.

More Information:

The core functionality of the DataTable control operates without any major issues on high-end mobile platforms. Implementers should keep in mind the impact that limited real estate may have on end users of the DataTable and be aware of the following preliminary list of smart phone known issues:

  • Meta-key multi-selection is not supported.
  • Fixed scrolling is not supported.
  • Resizeable Columns are not supported.
  • Inline editing is not fully supported across all platforms and should be well tested in your application. Specifically, input via textbox is not supported on the Nokia N95, and radio buttons and textbox input validation are not supported on the iPhone.

Support & Community

The YUI Library and related topics are discussed on the on the ydn-javascript mailing list.

In addition, please visit the YUIBlog for updates and articles about the YUI Library written by the library's developers.

Filing Bugs & Feature Requests

The YUI Library's public bug tracking and feature request repositories are located on the YUI SourceForge project site. Before filing new feature requests or bug reports, please review our reporting guidelines.

Cheat Sheet for the DataTable Control:

Cheat Sheet for the DataTable Control.

Download full set of cheat sheets.

More Reading about the YUI DataTable Control:

YUI DataTable on del.icio.us:

Copyright © 2008 Yahoo! Inc. All rights reserved.

Privacy Policy - Terms of Service - Copyright Policy - Job Openings