* @license PHP License * @package WB * @subpackage db */ WBClass::load('WBDatasource_FormAttribute'); /** * Populate form element's values with user ids * * Select users with clause and or by user group * * @version 0.2.0 * @package WB * @subpackage db */ class WBDatasource_FormAttribute_TableRelation extends WBDatasource_FormAttribute { /** * configuration parameter * @var array */ protected $config = array( 'ajaxupdate' => '', 'labelcolumns' => array('surname','forename'), 'labelformat' => '%s, %s', 'table' => 'user', 'relationtable' => 'usergroup', 'relationvalue' => array(1), 'foreigntable' => 'group', 'clause' => array( array( 'field' => 'approved', 'value' => 1 ) ), 'order' => array( array( 'field' => 'surname', 'asc' => 1 ), array( 'field' => 'forename', 'asc' => 1 ) ) ); /** * table * @var WBDatasource_Table */ protected $table; /** * get attribute's value * * Use dicktionary to fetch list of values * * @param mixed $current actual attribute value * @return array */ protected function getAttributeValue($current) { $this->prepareAjax(); $this->table = WBClass::create('WBDatasource_Table'); if (!is_array($current)) { $current = array(); } $clause = $this->config['clause']; if (!is_array($clause)) { $clause = array(); } $options = array('limit' => 0); if (!empty($this->config['order'])) { $options['order'] = $this->config['order']; } $this->injectRelation($clause, $options); $list = $this->table->get($this->config['table'], null, null, $clause, $options); if (empty($list)) { return $current; } // append list $primary = $this->table->getIdentifier($this->config['table']); foreach ($list as $v => $l) { $cols = array(); foreach ($this->config['labelcolumns'] as $lc) { $cols[] = $l[$lc]; } $current[] = array( 'value' => $l[$primary], 'label' => vsprintf($this->config['labelformat'], $cols), 'checked' => 'yes' ); } return $current; } /** * Inject group attributes in clause and options * * Allow to select users by group * * @param array $clause * @param array $options */ private function injectRelation(&$clause, &$options) { if (!is_array($this->config['relationvalue'])) { $this->config['relationvalue'] = array(trim($this->config['relationvalue'])); } // add join to options $options['join'] = array(); $options['join'][] = array( 'table' => $this->config['relationtable'], 'using' => $this->table->getIdentifier($this->config['table']) ); $clause[] = array( 'table' => $this->config['relationtable'], 'field' => $this->table->getIdentifier($this->config['foreigntable']), 'relation' => 'in', 'value' => $this->config['relationvalue'] ); } private function prepareAjax() { if (empty($this->config['ajaxupdate'])) { return; } $name = $this->element->getAttribute('name'); $observable = addslashes($this->config['ajaxupdate']); WBHtml_JS::add('WB/Ajax/Form/Element/TableRelation'); WBHtml_JS::add(sprintf('new WB.Ajax.Form.Element.TableRelation("%s", "%s");', $name, $observable), WBHtml_JS::AREA_FOOT); } }