xref: /plugin/struct/helper/field.php (revision 3ad9c1eaefd634b03b03b85327536e38c6df025a)
1<?php
2use plugin\struct\meta\Column;
3use plugin\struct\meta\Schema;
4use plugin\struct\meta\StructException;
5use plugin\struct\meta\Value;
6
7/**
8 * Allows adding a single struct field as a bureaucracy field
9 *
10 * This class is used when a field of the type struct_field is encountered in the
11 * bureaucracy syntax.
12 */
13class helper_plugin_struct_field extends helper_plugin_bureaucracy_field {
14
15    /** @var  Column */
16    public $column;
17
18    /**
19     * Initialize the appropriate column
20     *
21     * @param array $args
22     */
23    public function initialize($args) {
24        parent::initialize($args);
25
26        // find the column
27        try {
28            $this->column = $this->findColumn($this->opt['label']);
29        } catch(StructException $e) {
30            msg(hsc($e->getMessage()), -1);
31        }
32    }
33
34    /**
35     * Validate the field
36     *
37     * @throws Exception
38     */
39    protected function _validate() {
40        parent::_validate(); // checks optional state stuff
41        if(!$this->column) return;
42        $this->opt['value'] = $this->column->getType()->validate($this->opt['value']);
43    }
44
45    /**
46     * Creates the HTML for the field
47     *
48     * @param array $params
49     * @param Doku_Form $form
50     * @param int $formid
51     */
52    public function renderfield($params, Doku_Form $form, $formid) {
53        if(!$this->column) return;
54
55        // this is what parent does
56        $this->_handlePreload();
57        if(!$form->_infieldset) {
58            $form->startFieldset('');
59        }
60        if($this->error) {
61            $params['class'] = 'bureaucracy_error';
62        }
63
64        // output the field
65        $value = new Value($this->column, $this->opt['value']);
66        $field = action_plugin_struct_entry::makeField($value, $params['name']);
67        $form->addElement($field);
68    }
69
70    /**
71     * Tries to find the correct column and schema
72     *
73     * @throws StructException
74     * @param string $colname
75     * @return \plugin\struct\meta\Column
76     */
77    protected function findColumn($colname) {
78        list($table, $label) = explode('.', $colname, 2);
79        if(!$table || !$label) {
80            throw new StructException('Field \'%s\' not given in schema.field form', $colname);
81        }
82        $schema = new Schema($table);
83        return $schema->findColumn($label);
84    }
85
86    /**
87     * This ensures all language strings are still working
88     *
89     * @return string always 'bureaucracy'
90     */
91    public function getPluginName() {
92        return 'bureaucracy';
93    }
94
95}
96