Server-driven table definition, pagination and sorting

This example builds a DataTable based on the columns information taken from the server. Instead of building a statically defined DataTable it will build it on what the server says. It also does server-side paging and sorting.

The information about the nature of the data comes along the data itself when requested by adding the URL attribute meta=true. The server will then add a meta property to the reply with the requested information.

We override the method doBeforeParseData to extract that information, since we need it for parsing. Up to that point, the reply is converted to a JavaScript object but the fields have not been parsed yet. We also extract column definitions to set up the DataTable.

We also override the method doBeforeCallback because we also need to tell the DataTable the total number of records in the database, not those in the reply, which is only a page long

Server-side Paging is greatly simplified in 2.5. There is a configuration attribute called paginationEventHandler which is usually set to the function that does client-side paging. If you want to do server-side paging, you just set it to YAHOO.widget.DataTable.handleDataSourcePagination. This handler will check if the page requested has been loaded and, if not, it will reuse the DataSource to request the required page, which it will place in the RecordSet in its correct position. The Recordset thus acts as a cache. If you skip over pages, the RecordSet will have gaps but JavaScript does not waste space on non-existing array elements.

The server-side pagination handler uses a default method to assemble the URL arguments. If you want to change the name of the arguments or add extra information you override it by setting the generateRequest configuration attribute. This function should return the string of URL arguments to be appended to the base URL set up in the DataSource. Since we are doing sorting besides paging, we need to add the information contained in the sortedBy configuration attribute.

Finally, we override the sortColumn method so that instead of doing sorting on the client side, we do it on the server side. We could not possibly do sorting on the client since we don't have all the records there, the RecordSet is full of gaps so, instead of actually sorting the RecordSet we flush it and make the paging handler request a new page one, this time sorted as requested.

The source files for this sample are available for download in a zip file. The PHP server script requires an active PHP interpreter. The YUI compoments are fetched from the YUI site.

Source files (zipped)