1: <?php
2:
3: /**
4: * This file is part of the Nette Framework (http://nette.org)
5: *
6: * Copyright (c) 2004 David Grudl (http://davidgrudl.com)
7: *
8: * For the full copyright and license information, please view
9: * the file license.txt that was distributed with this source code.
10: * @package Nette\Forms\Controls
11: */
12:
13:
14:
15: /**
16: * Select box control that allows multiple item selection.
17: *
18: * @author David Grudl
19: * @package Nette\Forms\Controls
20: */
21: class NMultiSelectBox extends NSelectBox
22: {
23:
24:
25: /**
26: * Returns selected keys.
27: * @return array
28: */
29: public function getValue()
30: {
31: $allowed = array_keys($this->allowed);
32: if ($this->getPrompt()) {
33: unset($allowed[0]);
34: }
35: return array_intersect($this->getRawValue(), $allowed);
36: }
37:
38:
39:
40: /**
41: * Returns selected keys (not checked).
42: * @return array
43: */
44: public function getRawValue()
45: {
46: if (is_scalar($this->value)) {
47: $value = array($this->value);
48:
49: } elseif (!is_array($this->value)) {
50: $value = array();
51:
52: } else {
53: $value = $this->value;
54: }
55:
56: $res = array();
57: foreach ($value as $val) {
58: if (is_scalar($val)) {
59: $res[] = $val;
60: }
61: }
62: return $res;
63: }
64:
65:
66:
67: /**
68: * Returns selected values.
69: * @return array
70: */
71: public function getSelectedItem()
72: {
73: if (!$this->areKeysUsed()) {
74: return $this->getValue();
75:
76: } else {
77: $res = array();
78: foreach ($this->getValue() as $value) {
79: $res[$value] = $this->allowed[$value];
80: }
81: return $res;
82: }
83: }
84:
85:
86:
87: /**
88: * Returns HTML name of control.
89: * @return string
90: */
91: public function getHtmlName()
92: {
93: return parent::getHtmlName() . '[]';
94: }
95:
96:
97:
98: /**
99: * Generates control's HTML element.
100: * @return NHtml
101: */
102: public function getControl()
103: {
104: $control = parent::getControl();
105: $control->multiple = TRUE;
106: return $control;
107: }
108:
109:
110:
111: /**
112: * Count/length validator.
113: * @param NMultiSelectBox
114: * @param array min and max length pair
115: * @return bool
116: */
117: public static function validateLength(NMultiSelectBox $control, $range)
118: {
119: if (!is_array($range)) {
120: $range = array($range, $range);
121: }
122: $count = count($control->getSelectedItem());
123: return ($range[0] === NULL || $count >= $range[0]) && ($range[1] === NULL || $count <= $range[1]);
124: }
125:
126: }
127: