1: <?php
2:
3: 4: 5: 6:
7:
8: namespace Nette\Forms\Controls;
9:
10: use Nette;
11:
12:
13: 14: 15:
16: class SelectBox extends ChoiceControl
17: {
18:
19: const VALID = ':selectBoxValid';
20:
21:
22: private $options = [];
23:
24:
25: private $prompt = false;
26:
27:
28: private $optionAttributes = [];
29:
30:
31: public function __construct($label = null, array $items = null)
32: {
33: parent::__construct($label, $items);
34: $this->setOption('type', 'select');
35: $this->addCondition(Nette\Forms\Form::BLANK)
36: ->addRule([$this, 'isOk'], Nette\Forms\Validator::$messages[self::VALID]);
37: }
38:
39:
40: 41: 42: 43: 44:
45: public function setPrompt($prompt)
46: {
47: $this->prompt = $prompt;
48: return $this;
49: }
50:
51:
52: 53: 54: 55:
56: public function getPrompt()
57: {
58: return $this->prompt;
59: }
60:
61:
62: 63: 64: 65:
66: public function setItems(array $items, $useKeys = true)
67: {
68: if (!$useKeys) {
69: $res = [];
70: foreach ($items as $key => $value) {
71: unset($items[$key]);
72: if (is_array($value)) {
73: foreach ($value as $val) {
74: $res[$key][(string) $val] = $val;
75: }
76: } else {
77: $res[(string) $value] = $value;
78: }
79: }
80: $items = $res;
81: }
82: $this->options = $items;
83: return parent::setItems(Nette\Utils\Arrays::flatten($items, true));
84: }
85:
86:
87: 88: 89: 90:
91: public function getControl()
92: {
93: $items = $this->prompt === false ? [] : ['' => $this->translate($this->prompt)];
94: foreach ($this->options as $key => $value) {
95: $items[is_array($value) ? $this->translate($key) : $key] = $this->translate($value);
96: }
97:
98: return Nette\Forms\Helpers::createSelectBox(
99: $items,
100: [
101: 'disabled:' => is_array($this->disabled) ? $this->disabled : null,
102: ] + $this->optionAttributes,
103: $this->value
104: )->addAttributes(parent::getControl()->attrs);
105: }
106:
107:
108: 109: 110:
111: public function addOptionAttributes(array $attributes)
112: {
113: $this->optionAttributes = $attributes + $this->optionAttributes;
114: return $this;
115: }
116:
117:
118: 119: 120:
121: public function isOk()
122: {
123: return $this->isDisabled()
124: || $this->prompt !== false
125: || $this->getValue() !== null
126: || !$this->options
127: || $this->control->size > 1;
128: }
129: }
130: