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