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 cell editing.

YUI community member Daniel Barreiro (screen name Satyam) has contributed two terrific articles on the YUI DataTable Control on YUIBlog:

In addition to reading this User's Guide and the canonical DataTable examples by DataTable author Jenny Han Donnelly, we strongly recommend that you review Satyam's work in preparing for your DataTable implementation.

Note: The 2.6.0 release of DataTable introduces the ScrollingDataTable and CellEditor classes, the Paginator widget is now offered as a standalone component, and significant changes have been applied to DataTable's pagination and sorting architectures. While backward compatibility has been maintained whenever possible, the Paginator widget is now an optional dependency, and custom extensions to inline cell editing or server-side pagination and/or sorting will likely need to be updated to be compatible with the new models. Implementers who are upgrading from an earlier version are strongly advised to read the Upgrades Notes.

Upgrade Notes

Users new to DataTable can skip this section and proceed directly to the Getting Started section. Implementers who are upgrading from previous versions should note the following changes for version 2.6.0:

  • Paginator has been extracted as a standalone class and optional dependency.
  • Functionality for xy-scrollability has been ported to YAHOO.widget.ScrollingDataTable, a subclass of YAHOO.widget.DataTable. Non-scrolling DataTables will no longer generate any extraneous markup that is an artifact of the scrolling architecture. Only ScrollingDataTables will generate the additional markup needed to support xy-scrolling. Implementers should instantiate a ScrollingDataTable directly by calling new YAHOO.widget.ScrollingDataTable. For backward compatibility, a ScrollingDataTable instance will also be returned if {scrollable:true} is passed to the constructor for DataTable.
  • Inline cell editing functionality has been re-implemented as YAHOO.widget.CellEditor and related subclasses. The following methods are no longer supported:
    • DataTable.editCheckbox() has been removed. The CheckboxCellEditor class should be used instead.
    • DataTable.editDate() has been removed. The DateCellEditor class should be used instead.
    • DataTable.editDropdown() has been removed. The DropdownCellEditor class should be used instead.
    • DataTable.editRadio() has been removed. The RadioCellEditor class should be used instead.
    • DataTable.editTextarea() has been removed. The TextareaCellEditor class should be used instead.
    • DataTable.editTextbox() has been removed. The TextboxCellEditor class should be used instead.
    • showCellEditorBtns() has been removed. The CellEditor method renderBtns() should be used instead.
    • editorUpdateEvent has been removed.
    • resetCellEditor() has been renamed to destroyCellEditor().
  • The values for CellEditor checkboxOptions, dropdownOptions, and radioOptions must be either a simple Array or an Array of object literals with properties "value" and "label". Backward compatibility is not being supported in this area, so please update your implementations as needed.
  • A new CellEditor property asyncSubmitter can be used to submit input values and will block the DataTable UI (via new DataTable methods disable() and undisable()) until the callback function is executed to finish the transaction.
  • The CellEditor's "Save" and "Cancel" buttons now have configurable labels.
  • CellEditor validator functions, including the built-in function YAHOO.widget.DataTable.validateNumber must return undefined for invalid values instead of null.
  • Pagination and sorting have been significantly reworked to better support dynamically driven DataTables. As a result, the following important changes have been made:
    • Removed support for all "magic meta" fields. Server-provided values, such as totalRecords will need to be explicitly updated by custom implementation code as described in the Server-side Sorting and Pagination of Dynamic Data section.
    • The following APIs have been removed:
      • paginationEventHandler Attribute
      • handleSimplePagination()
      • handleDataSourcePagination()
      • updatePaginator()
      • showPage()
      • formatPaginator()
      • formatPaginationDropdown()
      • formatPaginatorLinks()
    • The dynamicData Attribute has been added to better support server-side pagination and/or sorting.
    • The onPaginatorChange() method has been renamed to onPaginatorChangeRequest()
    • Removed backward compatibility support for the paginated Attribute and the object literal paginator Attribute value. Implementers must use the Paginator class to populate the paginator Attribute.
  • The following APIs have been changed from static class properties to instance Attributes, to be set via the initial config or myDataTable.set():
    • MSG_EMPTY
    • MSG_ERROR
    • MSG_LOADING
    • COLOR_COLUMNFILLER (moved to ScrollingDataTable class)
  • The formatTheadCell() method been changed from static a static method to an instance method with an update to its argument signature.
  • The initEvent will fire when rows are rendered from an initialized state, and the renderEvent will always fire when rows are rendered, and also when the underlying DOM incrementally changes (such as adding or deleting rows or Columns). This is a change from prior behavior, when the renderEvent would *not* fire if the initEvent was fired and only when the entire view was rendered (such as a new page load).
  • For consistency with other "doBefore" abstract methods, doBeforeShowCellEditor() now returns true by default and returns false to cancel showing the cell editor.
  • The Column property minWidth default value is now null.
  • Added Column property maxAutoWidth.
  • In the generated markup, the primary data TBODY is (once again) in the DOM before the message TBODY element.
  • Resizeable Columns now create an additional resizer liner DIV element between the TH element and the liner DIV element. Implementers are advised to access the liner DIV elements via Column method getThLinerEl() rather than directly accessing the DOM via TH.firstChild.
  • TR element IDs are now assigned with the corresponding Record ID, and the heretofore unused TD IDs have been removed.
  • All CSS classes representing Column states are now assigned directly on TH and TD elements, not on liner DIV elements.

Getting Started

To use the DataTable control, include the following source files in your web page.

END; echo(syntaxHighlight($html, 'html')); ?>

Object Model and DOM 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.

  • ColumnSet The ColumnSet is a set of Column instances. Each Column represents a field of data from the DataSource. Each Column is assigned
    • a unique key which names the Column (one is created if not provided)
    • a field which maps to a field defined in the DataSource schema
    • a key index which represents its order within the ColumnSet
    • an ID which is a globally unique identifier across all ColumnSets
  • RecordSet The RecordSet is a set of Record instances, each of which represents a row of data. Each Record is assigned
    • a globally unique ID, which remains constant regardless of sort order
    • 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> is assigned a Record instance to display, and its unique DOM ID is assigned its corresponding Record's ID. If the DataTable is paginated, then the <table> will show only a subset of the entire RecordSet.
  • DataTable The DataTable class manages the interaction between the ColumnSet, the RecordSet, and DOM Elements and exposes the API through which developers can build and configure their tables.
  • ScrollingDataTable The ScrollingDataTable class extends the DataTable class to add functionality specific to xy-scrolling.

The markup created for each DataTable instance starts with the implementer-provided container, into which a <table> element is create. Within the <table> element, two <tbody> elements are created: a message <tbody> element to display stateful messages such as "Loading data..." or "No data found" and also a primary <tbody> element that contains the cells of data.

In the case of a ScrollingDataTable, there are actually two <table> elements, each housed in its own container, identified as the "header container" and the "body container". The <table> in the header container consists of a <table> element with only a <thead> element of Column header <th>s, whose purpose is to remain fixed on the screen when the body cells scroll vertically. The <table> generated into the body container is nearly identical to the <table> created by the DataTable class, with the exception of the <thead> element which is placed offscreen for screenreader consumption only.

The following markup is a generic sample of the DOM elements that are generated by the DataTable class. Note that Column keys are also assigned as CSS class names on DOM elements so they can be used as hooks to skin or customize the UI. As such Column keys are subject to string validation before being used in the DOM or in CSS. Please see the Column Keys Usage section for more information.

END; echo(syntaxHighlight($html, 'html')); ?>

Understanding Records, Rows, and DOM Elements

The DataTable API provides a set of methods for implementers to manipulate underlying data and associated DOM elements, such as addRow(), updateRow(), and deleteRow(). Calling addRow(oData) on the DataTable will add a new Record of data to 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.

When pagination is enabled, 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 when pagination is enabled.

Instantiating DataTable

A DataTable is instantiated by passing in the following to the constructor:

  1. An ID string or element reference to a container DIV element to host the rendered markup
  2. A set of Column definitions
  3. A DataSource instance to manage data retrieval from a variety of sources, from local JavaScript arrays to remote online servers. Please refer to the DataSource documentation for more information on using this utility.

The Container Element

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.

Column Definitions

The second argument of the DataTable constructor is an array of object literals to define the Columns that are rendered into the table. In the simple example below, we define our DataTable to display three Columns, which we name "fname", "lname", and "age":

The following Column properties are supported:

Column properties
PropertyTypeDescription
keyStringThe unique name assigned to each Column. When a Column key maps to a DataSource field, cells of the Column will automatically populate with the corresponding data. If a key is not defined in the Column definition, one will be auto-generated. Please see the Column Keys section for more uses.
fieldStringThe DataSource field mapped to the Column. By default, the field value is assigned to be the Column's key. Implementers may specify a different field explicitly in the Column definition. This feature is useful when mapping multiple Columns to a shared field, since keys must remain unique, or when the field name contains characters invalid for DOM or CSS usage (see the Column Keys section for more information).
labelStringBy default, the <th> element is populated with the Column's key. Supply a label to display a different header.
abbrStringValue for the <th> element's abbr attribute.
childrenObject[]An array of object literals that define nested child Columns of a Column.
classNameStringA custom CSS className or array of classNames to be applied to every cell of the Column.
editorStringString pointer to a CellEditor class.
editorOptionsObjectObject literal CellEditor-specific configuration options. Please refer to the API documentation for more information on which properties are supported for each type of CellEditor.
formatterString | HTMLFunctionA function or a pointer to a function to handle HTML formatting of cell data.
hiddenBooleanTrue if Column is hidden.
maxAutoWidthNumberUpper limit pixel width that a Column should auto-size to when its width is not set. Please note that maxAutoWidth validation is executed after cells are rendered, which may cause a visual flicker of content, especially on non-scrolling DataTables.
minWidthNumberMinimum pixel width. Please note that minWidth validation is executed after cells are rendered, which may cause a visual flicker of content, especially on non-scrolling DataTables.
resizeableBooleanTrue if Column is resizeable. The Drag & Drop Utility is required to enable this feature. Only bottom-level and non-nested Columns are resizeble.
selectedBooleanTrue if Column is selected.
sortableBooleanTrue if Column is sortable.
sortOptionsObjectObject literal of configurations for sort behavior.
  • defaultDir "asc", "desc", YAHOO.widget.DataTable.CLASS_ASC, or YAHOO.widget.CLASS_DESC
  • sortFunction Custom sort function.
widthNumberPixel width.

Basic Features

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

Column Keys Usage

Unique Column keys are assets that tie together data consumption and UI rendering in DataTable. When a Column key maps to a DataSource field, cells of the Column will automatically populate with the corresponding data. When a key does not map to a DataSource field, the cell will be left blank or can be populated manually, through the use of a formatter.

Column keys are also assigned as classnames to allow CSS hooks for customizing the UI. Defining custom CSS for ".yui-dt-col-myKey" and/or ".yui-dt-col-myKey .yui-dt-liner" lets you easily define styles per Column.

Internal usage of Column keys in the document include element IDs, names, classnames, headers, and href attributes, as well as selectors in dynamically created CSS rules. To support this kind of usage, Column keys must first be sanitized, to strip the string of characters that may be problematic for CSS and DOM usage (i.e., make sure it contains only letters, numbers, hyphen, or underscore). If your DataSource field contains characters that are invalid for DOM and/or CSS usage, it is recommended that you define the Column key as a simple alphanumeric string and also define a Column field that points to the problematic DataSource field.

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.

AAA BBB CCC
1 bbb ccc
2 bbb ccc
3 bbb ccc
END; echo(syntaxHighlight($html, 'html')); ?>

Implementers should note that form elements and elements attached to DOM event listeners may not be parsed correctly. Custom parsers should be used to extract data values out of form elements, and formatters should be used to reconstruct form elements programmatically. Likewise, DOM event listeners will be unattached from the original elements and implementers should listen for the corresponding DataTable Custom Events to rewire any lost functionality.

By default, DataSources with responseType = YAHOO.util.DataSource.TYPE_HTMLTABLE, iterate over all TR elements of all TBODY elements of the given TABLE to parse out data. If there are any non-data elements (like summary rows or the message TBODY in DataTable), they should first be removed from the DOM.

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 DataTable 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.

If you don't define any formatter, DataTable's default formatter will take your cell's data value as markup and insert it into the DOM with innerHTML. If you are using data from a third-party source, user input data, or any other untrustworthy source, it is highly recommended you point to the "text" formatter, which will HTML-escape data values for safer insertion into the DOM. See the Security Considerations section for more information.

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

Please note that not all features are compatible with nested Columns. Specifically, Columns that have children can not be resized, and Columns that are children can neither be hidden/shown nor dragged-and-dropped.

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:

Specifying a sortOptions.field value will point the sort to be executed on the given field.

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

Note: As of the 2.6.0 release, passing scrollable:true to the DataTable constructor will actually instantiate the subclass ScrollingDataTable. This change means that scrolling cannot be enabled or disabled dynamically at runtime, and implementers who want the scrolling feature must specify it at instantiation, by calling the ScrollingDataTable constructor directly, or alternately either by passing in the config scrollable:true to the DataTable constructor. APIs that are relevant and necessary only for the scrolling feature have been moved to the ScrollingDataTable subclass and are no longer available from the DataTable class.

Implementers should keep in mind that the scrolling feature inherently entails a performance overhead that may impact user experience. Defining pixel widths for as many Columns as possible, disabling drag-and-drop resizing, and keeping your data size manageable will go a long way towards reducing that overhead.

To enable scrolling, call the YAHOO.widget.ScrollingDataTable constructor 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. When a height is set, it defines the height of the vertically scrolling body of the table, not including headers.

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. The ideal value should be determined per implementation since there are no hard and fast rules, only general guidelines:

  • By default renderLoopSize is 0, so all rows are rendered in a single loop. A renderLoopSize > 0 adds overhead so use thoughtfully.
  • If your set of data is large enough (number of rows X number of Columns X formatting complexity) that users experience latency in the visual rendering and/or it causes the script to hang, consider setting a renderLoopSize.
  • A renderLoopSize under 50 probably isn't worth it. A renderLoopSize > 100 is probably better.
  • A data set is probably not considered large enough unless it has hundreds and hundreds of rows.
  • Having a renderLoopSize > 0 and < total rows does cause the table to be rendered in one loop (same as renderLoopSize = 0) but it also triggers functionality such as post-render row striping to be handled from a separate setTimeout thread.

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 method selectColumn() also allows 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. Assign a CellEditor instance to the editor property in your Column definition:

You can pass in configuration options into the CellEditor constructor as an object literal to customize certain behaviors of the editor, such as input validation or default values. Please refer to the API documentation for more information on which properties are supported for each type of CellEditor.

Common CellEditor properties
PropertyTypeDescription
asyncSubmitterFunctionImplementer defined function that can submit the input value to a server. This function must accept the arguments fnCallback and oNewValue. When the submission is complete, the function must also call fnCallback(bSuccess, oNewValue) to finish the save routine in the CellEditor. This function can also be used to perform extra validation or input value manipulation.
defaultValueMixedDefault value to use in CellEditor if Record data value is undefined.
disableBtnsBooleanTrue if Save/Cancel buttons should not be displayed in the CellEditor.
LABEL_CANCELStringText to display on Cancel button.
LABEL_SAVEStringText to display on Save button.
validatorFunctionValidator function for input data returns either the validated (or type-converted) value or undefined. Implementers can use the built-in validator function YAHOO.widget.DataTable.validateNumber or provide their own custom function.

Data Retrieval

Customizing the DataSource Request Syntax

DataTable provides a built in generateRequest Attribute, which constructs a string-based request with a default syntax:

"sort={SortColumnKey}&dir={SortColumnDir}&startIndex={PaginationStartIndex}&results={PaginationRowsPerPage}"

The default syntax can be customized by setting a custom function for the generateRequest Attribute:

Loading 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 specify the request sent to the DataSource in the initial load, you can set that value via the initialRequest config:

You can further customize the initial 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:

Loading Data at Runtime

The DataTable provides built-in functions that can be used as callbacks to DataSource's sendRequest method:

onDataReturnInitializeTable
Draws a DataTable with the data provided. On an existing DataTable it will delete the current contents and states before drawing the new. It is the method that would be used with polling to refresh the DataTable with new data.
onDataReturnInsertRows
This method will insert new rows at the beginning of the DataTable, preserving the existing data and regardless of any sort order. The insertion index for the added records can be assigned to when sending the request to the DataSource, or by accessing oPayload.insertIndex with the doBeforeLoadData() method at runtime. If applicable, creates or updates corresponding TR elements.
onDataReturnAppendRows
Rows will be added to the end of the DataTable, preserving the existing records, regardless of sort order.
onDataReturnSetRows
This method will manage DataSource responses according to oPayload data to create Records at an index corresponding to the request (i.e., if data for page 3 was requested, the Records will be placed at an index corresponding to page 3).

Data can be loaded at runtime with a sendRequest() call to the DataSource, by passing in a DataTable method as a callback handler.

As a convenience, DataTable has a load() method that will send the initialRequest value to the DataSource, and point to the onDataReturnInitializeTable() built-in callback method . The method accepts a config object that can specify request, callback, and datasource values.

Manipulating The Data Payload

The handleDataReturnPayload() method gives implementers the opportunity to access and manipulate the data payload returned to the callback function. The payload object usually represents DataTable's state values, in order to preserve state across data requests. You can override the function like this:

Server-side Sorting and Pagination of Dynamic Data

When data is very dynamic in nature, or too large to store locally in JavaScript, sorting and pagination functionality is best implemented on the server side. When dynamicData is enabled, all pagination and sorting interactions trigger a DataSource request for the new set of data. State management is taken care of for you via an oState object literal which gets sent as a data payload of the sendRequest() method and then handled in callback function along with the response.

Please note: At this time, row and cell selections are not preserved across dynamicData page views. All selections are purged before requests are sent for new sort or pagination states. Selection preservation for these cases is not provided but should be achieved through custom code.

Often, server-side pagination relies on the server response to know the number of total results. By defining a totalRecords locator in your DataSource schema's metaFields, you can access this value to update DataTable's state at runtime before the response data gets loaded by customizing the handleDataReturnPayload() method.

When dynamicData is enabled, sorting or paginating will trigger a DataSource request for new data to reflect the state. By default, the request is formatted with the following syntax:

"sort={SortColumnKey}&dir={SortColumnDir}&startIndex={PaginationStartIndex}&results={PaginationRowsPerPage}"

The request that gets sent for each new state can be easily customized by defining a custom generateRequest function (see above).

Security Considerations

When providing HTML values to YUI APIs, implementers need to ensure these strings -- especially when containing data from third-party sources or user input data -- have been properly treated so they may safely be inserted into the DOM. The YAHOO.lang.escapeHTML() method is available for this purpose in version 2.9.0. The built-in "text" formatter (YAHOO.widget.DataTable.formatText) will HTML-escape all string values passed to it before rendering into the DataTable's DOM.

Custom Events, "doBefore" Abstract Methods, and "onEvent" Built-in Event Handlers

The DataTable control provides a robust Custom Event model to allow you to seamlessly integrate and expand upon its built-in fuctionality. Using Custom Events make it easy to react to user interactions like a cell click or a row click:

Another example is 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 of type String.

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

The doBeforeSortColumn() method gives implementers a hook to update the UI while sorting occurs.

The doBeforeShowCellEditor() method gives implementers access to the CellEditor instance before it is shown for a edit interaction.

The doBeforeLoadData() method gives implementers access to the DataSource response before it is consumed by the DataTable instance.

DataTable provides a set of built-in "onEvent" functions that are designed to integrate core functionality with user-driven events. Implementers can assign these functions as handlers to DataTable Custom Events to easily build a rich interactive experience.

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 YUILibrary.com for a complete list of known issues.

Draggable Columns Require "yui-skin-sam" Class on body Element

When draggable Columns are enabled and the "yui-skin-sam" class is not applied to the body element, the vertical line that indicates the drop target for the Column is not visible. The following custom CSS can be applied as a workaround for implementations that do not wish to apply the "yui-skin-sam" class on the body element.

Sub-optimal Performance for hideColumn() and showColumn() on IE<8

For DataTables bigger than a certain size, users on IE versions less than 8 may see performance issues when showing or hiding multiple Columns, as described here.

Issues When DataTable or Ancestor is Hidden

  • Widths are not correctly validated. Implementers should call the method onShow() after removing display = "none" on DataTable or ancestor to make sure widths are correctly validated when the widget is unhidden.
  • Borders remain visible in IE. 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.

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.

Table Caption Incompatibilies

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

Captions are not supported in ScrollingDataTables.

Opera performance issues with inline cell editing when scrolling is enabled

Opera users may see slow updates when inline cell editing while scrolling is enabled.

Opera Column Inconsistencies With ScrollingDataTable

In Opera, ScrollingDataTables 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.

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.
  • Scrolling is not supported on Android devices and requires two-finger scroll on iOS.
  • Resizeable Columns are not supported.
  • Inline cell 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.
  • XML is not currently supported on Android devices.