1: <?php
2:
3: /**
4: * This file is part of the Nette Framework (https://nette.org)
5: * Copyright (c) 2004 David Grudl (https://davidgrudl.com)
6: */
7:
8: namespace Nette\Forms\Controls;
9:
10: use Nette;
11:
12:
13: /**
14: * Select box control that allows single item selection.
15: */
16: class SelectBox extends ChoiceControl
17: {
18: /** validation rule */
19: const VALID = ':selectBoxValid';
20:
21: /** @var array of option / optgroup */
22: private $options = array();
23:
24: /** @var mixed */
25: private $prompt = FALSE;
26:
27:
28: /**
29: * Sets first prompt item in select box.
30: * @param string
31: * @return static
32: */
33: public function setPrompt($prompt)
34: {
35: $this->prompt = $prompt;
36: return $this;
37: }
38:
39:
40: /**
41: * Returns first prompt item?
42: * @return mixed
43: */
44: public function getPrompt()
45: {
46: return $this->prompt;
47: }
48:
49:
50: /**
51: * Sets options and option groups from which to choose.
52: * @return static
53: */
54: public function setItems(array $items, $useKeys = TRUE)
55: {
56: if (!$useKeys) {
57: $res = array();
58: foreach ($items as $key => $value) {
59: unset($items[$key]);
60: if (is_array($value)) {
61: foreach ($value as $val) {
62: $res[$key][(string) $val] = $val;
63: }
64: } else {
65: $res[(string) $value] = $value;
66: }
67: }
68: $items = $res;
69: }
70: $this->options = $items;
71: return parent::setItems(Nette\Utils\Arrays::flatten($items, TRUE));
72: }
73:
74:
75: /**
76: * Generates control's HTML element.
77: * @return Nette\Utils\Html
78: */
79: public function getControl()
80: {
81: $items = $this->prompt === FALSE ? array() : array('' => $this->translate($this->prompt));
82: foreach ($this->options as $key => $value) {
83: $items[is_array($value) ? $this->translate($key) : $key] = $this->translate($value);
84: }
85:
86: return Nette\Forms\Helpers::createSelectBox(
87: $items,
88: array(
89: 'selected?' => $this->value,
90: 'disabled:' => is_array($this->disabled) ? $this->disabled : NULL,
91: )
92: )->addAttributes(parent::getControl()->attrs);
93: }
94:
95:
96: /**
97: * Performs the server side validation.
98: * @return void
99: */
100: public function validate()
101: {
102: parent::validate();
103: if (!$this->isDisabled() && $this->prompt === FALSE && $this->getValue() === NULL && $this->options && $this->control->size < 2) {
104: $this->addError(Nette\Forms\Validator::$messages[self::VALID]);
105: }
106: }
107:
108: }
109: