1: <?php
2:
3: /**
4: * This file is part of the Nette Framework (https://nette.org)
5: * Copyright (c) 2004 David Grudl (https://davidgrudl.com)
6: */
7:
8: namespace Nette\Forms\Controls;
9:
10: use Nette;
11:
12:
13: /**
14: * Select box control that allows multiple items selection.
15: */
16: class MultiSelectBox extends MultiChoiceControl
17: {
18: /** @var array of option / optgroup */
19: private $options = [];
20:
21: /** @var array */
22: private $optionAttributes = [];
23:
24:
25: public function __construct($label = null, array $items = null)
26: {
27: parent::__construct($label, $items);
28: $this->setOption('type', 'select');
29: }
30:
31:
32: /**
33: * Sets options and option groups from which to choose.
34: * @return static
35: */
36: public function setItems(array $items, $useKeys = true)
37: {
38: if (!$useKeys) {
39: $res = [];
40: foreach ($items as $key => $value) {
41: unset($items[$key]);
42: if (is_array($value)) {
43: foreach ($value as $val) {
44: $res[$key][(string) $val] = $val;
45: }
46: } else {
47: $res[(string) $value] = $value;
48: }
49: }
50: $items = $res;
51: }
52: $this->options = $items;
53: return parent::setItems(Nette\Utils\Arrays::flatten($items, true));
54: }
55:
56:
57: /**
58: * Generates control's HTML element.
59: * @return Nette\Utils\Html
60: */
61: public function getControl()
62: {
63: $items = [];
64: foreach ($this->options as $key => $value) {
65: $items[is_array($value) ? $this->translate($key) : $key] = $this->translate($value);
66: }
67:
68: return Nette\Forms\Helpers::createSelectBox(
69: $items,
70: [
71: 'disabled:' => is_array($this->disabled) ? $this->disabled : null,
72: ] + $this->optionAttributes,
73: $this->value
74: )->addAttributes(parent::getControl()->attrs)->multiple(true);
75: }
76:
77:
78: /**
79: * @return static
80: */
81: public function addOptionAttributes(array $attributes)
82: {
83: $this->optionAttributes = $attributes + $this->optionAttributes;
84: return $this;
85: }
86: }
87: