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

Active Record Controller

MWP\Framework\Helpers\ActiveRecordController

An active record controller encapsulates all of the screens required to manage an active record. The default implementation provided by the framework includes these standard CRUD screens:

• An index screen which shows a display table of all records in the database
• A create screen which displays and processes the form for creating a new record
• An edit screen which displays and processes the form for editing an existing record
• A view screen which shows the currently stored values for an existing record
• A delete screen which confirms the deletion of an individual record

@Create A Controller

You can use an active record class to create a controller that manages its associated database records. You can customize many aspects of the active record controller through the config array passed when you create it.

RecordClass::createController( $key, $config ) > doc

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

add_action( 'mwp_framework_init', function() 
{    
    /**
     * Create a controller to manage our users
     *
     * - Add it to an admin page
     * - Use ajax for navigating the display table
     * - Include a role selection filter
     * - Allow sorting by user login or display name
     * - Allow searching by user display name, login name, or email
     */
    User::createController( 'admin', array(
        'adminPage' => [
            'title' => 'Users List',
            'type' => 'menu',
            'icon' => 'dashicons-admin-users',
            'position' => 71,
        ],
        'tableConfig' => [
            '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' => '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>';
                    },
                ],
            ],
        ],
    ));

    $controller = User::getController('admin');
});

@Get A Controller

Once you have created a controller for your active record class. You can retrieve its instance elsewhere in your code using the getController( $key ) static method on your active record class.

RecordClass::getController( $key ) > doc

use VendorName\PackageName\Models\User;

$controller = User::getController('admin');
wp_redirect( $controller->getUrl() );

@Use A Custom Controller

If you would like to expand on the existing screens provided by the default implementation by adding new ones, or customize the behavior of existing screens, then you can create your own class which extends the MWP\Framework\Helpers\ActiveRecordController class and assign it as the controller class for your active record before you begin creating.

RecordClass::setControllerClass( $class ) > doc

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

/* Extends MWP\Framework\Helpers\ActiveRecordController */
use VendorName\PackageName\Controllers\UserController;    

add_action( 'mwp_framework_init', function() 
{
    // Prepare a controller config
    $admin_controller_config = array( ... );

    // Use our own custom controller
    User::setControllerClass( UserController::class );
    User::createController( 'admin', $admin_controller_config );
});

@How A Controller Works

When a controller is created, the controller object instance is registered as a handler for all requests to the associated admin page defined in the controller configuration.

Any time the controller is going to handle rendering a page, the init() method on the controller is called which allows the controller to perform any pre-processing of the page request (such as internal setup, or authorization checks). When the page is loaded, the do_index() method on the controller instance is called to process the request and render the page.

If a &do=action parameter exists on the page request, then the method which is called to process the page changes to do_action(). The base active record controller handles requests for the following actions:

do_index() Renders an active record display table (no ‘do’ parameter in url, or do=index)
do_view() Renders an individual record view (do=view parameter in url)
do_edit() Renders a record editing form (do=edit parameter in url)
do_new() Renders a record creation form (do=new parameter in url)
do_delete() Confirms and deletes a record (do=delete parameter in url)

@Instance Method Reference

$instance->getActions()
/**
 * Get action buttons
 *
 * @return  array
 */
public function getActions()

This method is used to retrieve the action buttons which are displayed on the active record table. I.E. ‘Create A Record’.

/**
 * Get action buttons
 *
 * @return  array
 */
public function getActions()
{
    $recordClass = $this->recordClass;

    $actions = array( 
        'new' => array(
            'title' => __( $recordClass::$lang_create . ' ' . $recordClass::$lang_singular ),
            'params' => array( 'do' => 'new' ),
        )
    );

    if ( isset( $this->config['getActions'] ) and is_callable( $this->config['getActions'] ) ) {
        $actions = call_user_func( $this->config['getActions'], $actions, $this );
    }

    return is_array( $actions ) ? $actions : array();
}
Was this article helpful to you? Yes No

How can we help?