Overview
The tablelib provides a convenient class for displaying a table of data from a set of database tables. The table can be sorted, exported to various formats for download, paginated, filtered and more.
Usage
Steps
- Subclass table_sql
- Create a default constructor
- Setup table options
Example
This example will display a table of user records from the database.
Add some files for this example
This example will contain 2 files - one containing the table class and another one that will create a table and display it.
- test.php
- testusertable.class.php
Create 2 empty files with these names and put them in the root of your development moodle environment.
Subclass table_sql
In the file testusertable.class.php - create a subclass of sql_table.
<?php
defined('MOODLE_INTERNAL') || die();
require_once($CFG->libdir.'/tablelib.php');
class test_usertable extends table_sql {
}
</syntaxhighlight>
Add a constructor
Add a constructor to your class (you can pass arguments to your class if you like)
Call the parent constructor then setup your table options.
/**
* This table loads a list of users from the database.
*/
function __construct() {
parent::__construct('test_usertable');
}
The argument to the parent constructor is a unique id for the table and is used to store the user preferences for this table in the session (e.g. number of rows, sort order).
Setup table options
Modify the constructor to set the table baseurl so that pagination links link back to the correct page.
$this->define_baseurl(new moodle_url('/test.php'));
</syntaxhighlight>
Set the SQL for the query that loads the data.
Set the list of columns and headers.
Set no_sorting on the columns that cannot be sorted (generated?)
Set text_sorting on any text columns in the query (required for oracle)
Custom formatting for columns
Add a col_xxx function for each column that requires custom formatting (e.g adding html for a link).
Add other_cols for any columns which cannot be determined in advance.
See also
- The phpdoc comments on the class flexible_table and table_sql in tablelib.php
- Discussion in tracker