1
|
|
|
<?php
|
2
|
|
|
|
3
|
|
|
namespace AtDataGrid\Column;
|
4
|
|
|
|
5
|
|
|
use Zend\Db\Adapter\Adapter;
|
6
|
|
|
use Zend\Db\Sql\Sql;
|
7
|
|
|
use Zend\Form\Element\Select;
|
8
|
|
|
|
9
|
|
|
class DbReference extends Column
|
10
|
|
|
{
|
11
|
|
|
/**
|
12
|
|
|
* @var Adapter
|
13
|
|
|
*/
|
14
|
|
|
protected $dbAdapter;
|
15
|
|
|
|
16
|
|
|
/**
|
17
|
|
|
* @var string
|
18
|
|
|
*/
|
19
|
|
|
protected $refTable;
|
20
|
|
|
|
21
|
|
|
/**
|
22
|
|
|
* @var string
|
23
|
|
|
*/
|
24
|
|
|
protected $refField;
|
25
|
|
|
|
26
|
|
|
/**
|
27
|
|
|
* @var string
|
28
|
|
|
*/
|
29
|
|
|
protected $resultField;
|
30
|
|
|
|
31
|
|
|
/**
|
32
|
|
|
* @param $name
|
33
|
|
|
* @param Adapter $dbAdapter
|
34
|
|
|
* @param $refTable
|
35
|
|
|
* @param $refField
|
36
|
|
|
* @param $resultField
|
37
|
|
|
*/
|
38
|
|
|
public function __construct($name, Adapter $dbAdapter, $refTable, $refField, $resultField)
|
39
|
|
|
{
|
40
|
|
|
parent::__construct($name);
|
41
|
|
|
|
42
|
|
|
$this->dbAdapter = $dbAdapter;
|
43
|
|
|
$this->refTable = $refTable;
|
44
|
|
|
$this->refField = $refField;
|
45
|
|
|
$this->resultField = $resultField;
|
46
|
|
|
|
47
|
|
|
$sql = new Sql($this->dbAdapter, $this->refTable);
|
48
|
|
|
|
49
|
|
|
$this->addDecorator(new Decorator\DbReference($sql, $this->refField, $this->resultField));
|
50
|
|
|
|
51
|
|
|
// Form element
|
52
|
|
|
$this->setFormElement($this->buildFormElement());
|
53
|
|
|
}
|
54
|
|
|
|
55
|
|
|
/**
|
56
|
|
|
* @param string $identityColumn
|
57
|
|
|
* @param bool $addEmptyOption
|
58
|
|
|
* @return Select
|
59
|
|
|
*/
|
60
|
|
|
protected function buildFormElement($identityColumn = 'id', $addEmptyOption = true)
|
61
|
|
|
{
|
62
|
|
|
$sql = new Sql($this->dbAdapter, $this->refTable);
|
63
|
|
|
$select = $sql->select();
|
64
|
|
|
$statement = $sql->prepareStatementForSqlObject($select);
|
65
|
|
|
$rowset = $statement->execute();
|
66
|
|
|
|
67
|
|
|
$options = [];
|
68
|
|
|
foreach ($rowset as $row) {
|
69
|
|
|
$options[$row[$identityColumn]] = $row[$this->resultField];
|
70
|
|
|
}
|
71
|
|
|
|
72
|
|
|
$formElement = new Select($this->getName());
|
73
|
|
|
$formElement->setValueOptions($options);
|
74
|
|
|
|
75
|
|
|
if ($addEmptyOption) {
|
76
|
|
|
$formElement->setEmptyOption('');
|
77
|
|
|
}
|
78
|
|
|
|
79
|
|
|
return $formElement;
|
80
|
|
|
}
|
81
|
|
|
} |