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