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