1. Home
  2. Docs
  3. Application Framework
  4. Classes & Patterns
  5. Active Record Table

Active Record Table

MWP\Framework\Helpers\ActiveRecordTable

An active record table is used to display a customized listing of active records. Once rendered, an active record table gives the end user a paged visualization of the associated records in the database.

RecordClass::createDisplayTable( $args ) > doc

Note: It’s possible to customize the class used when creating a display table for your active record by using the ActiveRecord::setTableClass() method on your ActiveRecord. See doc

@Example Code

/* Extends MWP\Framework\Pattern\ActiveRecord */
use VendorName\PackageName\Models\User;

/* Extends MWP\Framework\Helpers\ActiveRecordTable */
use VendorName\PackageName\Helpers\UserTable;

// Optionally use our own implementation of the active record table
User::setTableClass( UserTable::class );

// Create an instance of the table helper
$table = User::createDisplayTable([
    'perPage' => 50,
    'sortBy' => 'display_name',
    'sortOrder' => 'ASC',
    'constructor' => [
        'ajax' => true,
    ],
    'columns' => [
        'display_name' => 'Display Name',
        'user_login' => 'Login Name',
        'user_email' => 'Email Address',
        'roles' => 'User Roles',
    ],
    'sortable' => [
        'display_name' => [ 'display_name', false ],
        'user_login' => [ 'user_login', false ],
    ],
    'searchable' => [
        'display_name' => [ 'type' => 'contains', 'combine_words' => 'AND' ],
        'user_email' => [ 'type' => 'contains' ],
        'user_login' => [ 'type' => 'contains' ],
    ],
    'handlers' => [
        'roles' => function( $row ) {
            $user = get_user_by('id', $row['ID']);
            $roles = wp_roles();
            return implode( ', ', array_map( function( $role ) use ( $roles ) { 
                return $roles->roles[ $role ]['name']; 
            }, $user->roles ) );
        },
    ],
    'extras' => [
        'role_filter' => [
            'init' => function( $table ) {
                if ( isset( $_REQUEST['role'] ) and $role = $_REQUEST['role'] ) {
                    $db = MWP\Framework\Framework::instance()->db();
                    $table->addFilter( array( "(SELECT COUNT(*) 
                        FROM {$db->base_prefix}usermeta AS meta 
                        WHERE meta.user_id=ID AND 
                            meta.meta_key='{$db->prefix}capabilities' AND 
                            meta.meta_value LIKE %s) > 0", "%\"{$role}\"%" ) );
                }
            },
            'output' => function( $table ) {
                $role = isset( $_REQUEST['role'] ) ? $_REQUEST['role'] : NULL;
                $roles = array_merge( [ '' => 'All Roles' ], wp_roles()->role_names );
                $options = array_map( function( $val, $title ) use ( $role ) { 
                    return sprintf( 
                        '<option value="%s" %s>%s</option>', 
                        $val, 
                        $role == $val ? 'selected' : '', 
                        $title 
                    ); 
                }, array_keys( $roles ), $roles );

                echo 'Filter By Role: 
                <select name="role" onchange="jQuery(this).closest(\'form\').submit()">' . 
                    implode( '', $options ) . 
                '</select>';
            },
        ],
    ],
]);

// Read url parameters to update the table query (such as sortby, order, search, etc)
$table->read_inputs();

// Query the items to display in the table
$table->prepare_items();

// Output the table
echo $table->getDisplay();

@Instance Attributes

$table->columns (array) An associative array of the columns to display in the table.
/**
 * @var array  {
 *     $columns = [
 *         'column_name' => 'Name of Column',
 *     ];
 * }
 */
public $columns = array();

Note: When specifying columns to display in the table, the column_name doesn’t actually have to map to an existing database column. If you use a column name that doesn’t map to an existing database column, use a handler to customize the output


$table->actionsColumn (string) The columns which the action links should be appended to
/**
 * @var string
 */
public $actionsColumn;

The action links are typically “Edit”, “View”, and “Delete”, however, they can be customized by overriding the getControllerActions() method in the associated active record class.


$table->handlers (array) Custom display handler callbacks for column data.
/**
 * @var array {
 *     $handlers = [
 *         'column_name' => function( $row ) {
 *             return '<strong>' . $row['column_name'] . '</strong>';
 *         }
 *     ];
 * }            
 */
public $handlers = array();

$table->bulkActions (array) An associative array of available bulk actions.
/**
 * @var array  {
 *     $bulkActions = [
 *         'delete' => 'Delete',
 *     ];
 * }
 */
public $bulkActions = array();

If the key for a bulk action item corresponds to a method name on the active record object, then that method will be called for each record in the selected set of records in the bulk action request. The mwp_fw_activerecord_bulk WordPress filter is called first to allow special handling of actions that do not correspond to a method on the records, or to selectively filter the records that the bulk action should apply to.

/**
 * Filter the records that are receiving the bulk action
 *
 * @param   array    $records       An array of active records from the bulk request
 * @param   string   $action        The requested bulk action
 * @param   string   $class         The name of the active record class
 * @return  array
 */
apply_filters( 'mwp_fw_activerecord_bulk', $records, $action, $class );

$table->sortableColumns (array) A list of columns that can be used for sorting.
/**
 * @var array {
 *     $sortableColumns = [
 *         'column_one' => 'column_one',         // Initially ascending
 *         'column_two' => ['column_two', true], // Initially descending
 *     ];
 * }
 */
public $sortableColumns = array();

$table->searchableColumns (array) A list of columns that are searchable.
/**
 * @var array {
 *     $searchableColumns = [
 *         'column_name' => [
 *             'type' => 'contains' or 'equals' // Search method
 *             'combine_words' => 'and' or 'or' // Used with 'contains' search
 *         ]
 *     ];
 * }
 */
public $searchableColumns = array();

$table->perPage (int) Number of records to show per page
/**
 * @var int 
 */
public $perPage = 50;

$table->sortBy (string) Default column to sort by
/**
 * @var string 
 */
public $sortBy;

$table->sortOrder (string) Default sort order
/**
 * @var string 
 */
public $sortOrder = 'DESC';

$table->displayTopNavigation (bool) Show the top page navigation on the table
/**
 * @var bool
 */
public $displayTopNavigation = true;

$table->displayBottomNavigation (bool) Show the bottom page navigation on the table
/**
 * @var bool
 */
public $displayBottomNavigation = true;

$table->displayTopHeaders (bool) Show the top headers on the table
/**
 * @var bool
 */
public $displayTopHeaders = true;

$table->displayBottomHeaders (bool) Show the bottom headers on the table
/**
 * @var bool
 */
public $displayBottomHeaders = false;

@Customizing Templates

You can customize the templates which are used for rendering your active record table by specifying different templates from your plugin, or overriding the existing ones in your plugin templates folder.

$table->tableTemplate (string) The table template to use for rendering
/**
 * @var string
 */
public $tableTemplate = 'views/management/records/table';

/**
 * Display the table
 */
public function display() 
{
    if ( $this->tableTemplate ) {
        echo $this->getPlugin()->getTemplateContent( $this->tableTemplate, array( 'table' => $this ) );
    } else {
        parent::display();
    }
}   

The table template is fetched from the plugin who owns the active record class.


$table->rowTemplate
/**
 * @var string
 */
public $rowTemplate = 'views/management/records/table_row';

/**
 * Generates content for a single row of the table
 *
 * @param   array  $item   The database row item
 */
public function single_row( $item ) 
{
    $recordClass = $this->activeRecordClass;

    if ( $this->rowTemplate ) {
        echo $this->getPlugin()->getTemplateContent( $this->rowTemplate, array(
            'table' => $this, 
            'item' => $item, 
        ));
    } else {
        parent::single_row( $item );
    }
}

The row template is fetched from the plugin who owns the active record class.


$table->rowActionsTemplate
/**
 * @var string
 */
public $rowActionsTemplate = 'views/management/records/row_actions';

/**
 * Get the row actions for an item
 *
 * @param   array       $item                       The item being acted upon
 * @param   string      $default_row_actions        The default provided core row actions
 * @return  string
 */
public function getControllerActionsHTML( $item, $default_row_actions='' )
{
    if ( $controller = $this->getController() ) {
        try {
            $recordClass = $this->activeRecordClass;
            $record = $recordClass::load( $item[ $recordClass::$prefix . $recordClass::$key ] );
            return $this->getPlugin()->getTemplateContent( $this->rowActionsTemplate, array( 
                'controller' => $controller, 
                'record' => $record, 
                'table' => $this, 
                'actions' => $record->getControllerActions(), 
                'default_row_actions' => $default_row_actions,
            ));
        } catch( \OutOfRangeException $e ) { }
    }
}

The row actions template is fetched from the plugin who owns the active record class.


@Instance Methods

$table->read_inputs()
/**
 * Read inputs
 *
 * This method will read script input parameters to the script and set the state 
 * of the table accordingly.
 *
 * @return   void
 */
public function read_inputs()

$table->prepare_items( $where )
/**
 * Prepare items by querying the database.
 *
 * @param  array   $where   An optional where clause to filter results by
 * @return void
 */
public function prepare_items( $where=array( '1=1' ) ) 

$table->getDisplay()
/**
 * Get the table display html
 *
 * @return  string
 */
public function getDisplay();
Was this article helpful to you? Yes No

How can we help?