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