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