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: */
11:
12: namespace Nette\Forms\Controls;
13:
14: use Nette;
15:
16:
17:
18: /**
19: * Select box control that allows multiple item selection.
20: *
21: * @author David Grudl
22: */
23: class MultiSelectBox extends SelectBox
24: {
25:
26:
27: /**
28: * Returns selected keys.
29: * @return array
30: */
31: public function getValue()
32: {
33: return array_intersect($this->getRawValue(), array_keys($this->allowed));
34: }
35:
36:
37:
38: /**
39: * Returns selected keys (not checked).
40: * @return array
41: */
42: public function getRawValue()
43: {
44: if (is_scalar($this->value)) {
45: return array($this->value);
46:
47: } else {
48: $res = array();
49: foreach ((array) $this->value as $val) {
50: if (is_scalar($val)) {
51: $res[] = $val;
52: }
53: }
54: return $res;
55: }
56: }
57:
58:
59:
60: /**
61: * Returns selected values.
62: * @return array
63: */
64: public function getSelectedItem()
65: {
66: return $this->areKeysUsed()
67: ? array_intersect_key($this->allowed, array_flip($this->getValue()))
68: : $this->getValue();
69: }
70:
71:
72:
73: /**
74: * Returns HTML name of control.
75: * @return string
76: */
77: public function getHtmlName()
78: {
79: return parent::getHtmlName() . '[]';
80: }
81:
82:
83:
84: /**
85: * Generates control's HTML element.
86: * @return Nette\Utils\Html
87: */
88: public function getControl()
89: {
90: return parent::getControl()->multiple(TRUE);
91: }
92:
93:
94:
95: /**
96: * Count/length validator.
97: * @param MultiSelectBox
98: * @param array min and max length pair
99: * @return bool
100: */
101: public static function validateLength(MultiSelectBox $control, $range)
102: {
103: if (!is_array($range)) {
104: $range = array($range, $range);
105: }
106: $count = count($control->getSelectedItem());
107: return ($range[0] === NULL || $count >= $range[0]) && ($range[1] === NULL || $count <= $range[1]);
108: }
109:
110: }
111: