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: 20: 21:
22: abstract class ChoiceControl extends BaseControl
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: public function setValue($value)
60: {
61: if ($value !== NULL && !array_key_exists((string) $value, $this->items)) {
62: $range = Nette\Utils\Strings::truncate(implode(', ', array_map(function ($s) { return var_export($s, TRUE); }, array_keys($this->items))), 70, '...');
63: throw new Nette\InvalidArgumentException("Value '$value' is out of allowed range [$range] in field '{$this->name}'.");
64: }
65: $this->value = $value === NULL ? NULL : key(array((string) $value => NULL));
66: return $this;
67: }
68:
69:
70: 71: 72: 73:
74: public function getValue()
75: {
76: return array_key_exists($this->value, $this->items) ? $this->value : NULL;
77: }
78:
79:
80: 81: 82: 83:
84: public function getRawValue()
85: {
86: return $this->value;
87: }
88:
89:
90: 91: 92: 93:
94: public function isFilled()
95: {
96: return $this->getValue() !== NULL;
97: }
98:
99:
100: 101: 102: 103: 104: 105:
106: public function setItems(array $items, $useKeys = TRUE)
107: {
108: $this->items = $useKeys ? $items : array_combine($items, $items);
109: return $this;
110: }
111:
112:
113: 114: 115: 116:
117: public function getItems()
118: {
119: return $this->items;
120: }
121:
122:
123: 124: 125: 126:
127: public function getSelectedItem()
128: {
129: $value = $this->getValue();
130: return $value === NULL ? NULL : $this->items[$value];
131: }
132:
133:
134: 135: 136: 137: 138:
139: public function setDisabled($value = TRUE)
140: {
141: if (!is_array($value)) {
142: return parent::setDisabled($value);
143: }
144:
145: parent::setDisabled(FALSE);
146: $this->disabled = array_fill_keys($value, TRUE);
147: if (isset($this->disabled[$this->value])) {
148: $this->value = NULL;
149: }
150: return $this;
151: }
152:
153: }
154: