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