1: <?php
2:
3: 4: 5: 6:
7:
8: namespace Nette\Forms\Controls;
9:
10: use Nette;
11:
12:
13: 14: 15: 16: 17: 18:
19: abstract class ChoiceControl extends BaseControl
20: {
21:
22: public $checkAllowedValues = TRUE;
23:
24:
25: private $items = array();
26:
27:
28: public function __construct($label = NULL, array $items = NULL)
29: {
30: parent::__construct($label);
31: if ($items !== NULL) {
32: $this->setItems($items);
33: }
34: }
35:
36:
37: 38: 39: 40:
41: public function loadHttpData()
42: {
43: $this->value = $this->getHttpData(Nette\Forms\Form::DATA_TEXT);
44: if ($this->value !== NULL) {
45: if (is_array($this->disabled) && isset($this->disabled[$this->value])) {
46: $this->value = NULL;
47: } else {
48: $this->value = key(array($this->value => NULL));
49: }
50: }
51: }
52:
53:
54: 55: 56: 57: 58: 59:
60: public function setValue($value)
61: {
62: if ($this->checkAllowedValues && $value !== NULL && !array_key_exists((string) $value, $this->items)) {
63: $set = Nette\Utils\Strings::truncate(implode(', ', array_map(function ($s) { return var_export($s, TRUE); }, array_keys($this->items))), 70, '...');
64: throw new Nette\InvalidArgumentException("Value '$value' is out of allowed set [$set] in field '{$this->name}'.");
65: }
66: $this->value = $value === NULL ? NULL : key(array((string) $value => NULL));
67: return $this;
68: }
69:
70:
71: 72: 73: 74:
75: public function getValue()
76: {
77: return array_key_exists($this->value, $this->items) ? $this->value : NULL;
78: }
79:
80:
81: 82: 83: 84:
85: public function getRawValue()
86: {
87: return $this->value;
88: }
89:
90:
91: 92: 93: 94:
95: public function isFilled()
96: {
97: return $this->getValue() !== NULL;
98: }
99:
100:
101: 102: 103: 104: 105: 106:
107: public function setItems(array $items, $useKeys = TRUE)
108: {
109: $this->items = $useKeys ? $items : array_combine($items, $items);
110: return $this;
111: }
112:
113:
114: 115: 116: 117:
118: public function getItems()
119: {
120: return $this->items;
121: }
122:
123:
124: 125: 126: 127:
128: public function getSelectedItem()
129: {
130: $value = $this->getValue();
131: return $value === NULL ? NULL : $this->items[$value];
132: }
133:
134:
135: 136: 137: 138: 139:
140: public function setDisabled($value = TRUE)
141: {
142: if (!is_array($value)) {
143: return parent::setDisabled($value);
144: }
145:
146: parent::setDisabled(FALSE);
147: $this->disabled = array_fill_keys($value, TRUE);
148: if (isset($this->disabled[$this->value])) {
149: $this->value = NULL;
150: }
151: return $this;
152: }
153:
154: }
155: