player.class.inc.php

This is an example of a PubKit class based on a custom database table. The table contains players in an orchestra, detailing their section and instrument:

The class's $columns property lists the fields that may be edited by PubKit and defines the item's normal sort order.

Although not a MODx resource, the item can use a MODx template variable for "section", as a category tag. The OptionButtons class extracts the TV's definition and displays it as a drop-down selection list. You need to keep the database field and the template variable in step with each other manually.

More than one selection-type TV can be attached to a record-based item, by listing them in the &tvs parameter. The sample Orchestra table (Player class) has a column named pro, associated with a checkbox defined in pkProfi. The parameter lists the TV name, the database column, the form field name and (optionally) CSS style to be used for the relevant HTML element: &tvs=`pkSection,section,section,pkSection;pkProfi,pro,pro`

When a Player item is saved, the value of the tag TV fields has to be copied to the right database table field in the class's own Save function. The modified fields array is then passed to the Save function in the parent class (Record), where all database columns with names matching elements of the $fields array are updated.

<?php
class Player extends Record
{
    public $name = 'Player';
    public $table = 'orchestra';
    public $columns = array('id','player','pro','section','instrument','rank','updated','published');
    public $sortOrder = 'section,rank';

    public $validate = array(
        'player'=>'string||Req||playerName',
        'section'=>'string||Req||sectionSelect'
        );

    public $delMsg;

function __construct($pid=0, $fields=array(), $lang) {
    parent::__construct($pid, $fields, $lang);
    $this->delMsg = $lang['del_player'] . $this->player .'?';
}


function Save($pid=NULL, $fields=array()) {
    if (!isset($this->rank) && empty($fields['rank'])) {
        $fields['rank'] = 1;
    }
    if (empty($fields['pro'])) {
        $fields['pro'] = 0;
    }
    parent::Save($pid, $fields);
}

function CustomFields($fields) {
// adjust for differences between field names and retrieved TV names for edit command
// set required format for dates and options sets (no widgets applied)
    global $modx;

    $customFields = array();
    foreach($this->columns as $column) {
        $customFields[$column] = $this->$column;
    }
    if (isset($this->tvs)) {
        foreach ($this->tvs as $tv) {
            if ($tv['field'] != $tv['column']) {
                $customFields[$tv['field'] ] = $this->$tv['column'];
                unset ($customFields[$tv['column'] ]);
            }
        }
    }
    return $customFields;
}

}
?>