| 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 |
declare (strict_types=1); |
| 8 |
namespace Packetery\Nette\Forms\Controls; |
| 9 |
|
| 10 |
use Packetery\Nette; |
| 11 |
/** |
| 12 |
* Select box control that allows multiple items selection. |
| 13 |
*/ |
| 14 |
class MultiSelectBox extends MultiChoiceControl |
| 15 |
{ |
| 16 |
/** @var array of option / optgroup */ |
| 17 |
private $options = []; |
| 18 |
/** @var array */ |
| 19 |
private $optionAttributes = []; |
| 20 |
public function __construct($label = null, array $items = null) |
| 21 |
{ |
| 22 |
parent::__construct($label, $items); |
| 23 |
$this->setOption('type', 'select'); |
| 24 |
} |
| 25 |
/** |
| 26 |
* Sets options and option groups from which to choose. |
| 27 |
* @return static |
| 28 |
*/ |
| 29 |
public function setItems(array $items, bool $useKeys = \true) |
| 30 |
{ |
| 31 |
if (!$useKeys) { |
| 32 |
$res = []; |
| 33 |
foreach ($items as $key => $value) { |
| 34 |
unset($items[$key]); |
| 35 |
if (\is_array($value)) { |
| 36 |
foreach ($value as $val) { |
| 37 |
$res[$key][(string) $val] = $val; |
| 38 |
} |
| 39 |
} else { |
| 40 |
$res[(string) $value] = $value; |
| 41 |
} |
| 42 |
} |
| 43 |
$items = $res; |
| 44 |
} |
| 45 |
$this->options = $items; |
| 46 |
return parent::setItems(\Packetery\Nette\Utils\Arrays::flatten($items, \true)); |
| 47 |
} |
| 48 |
public function getControl() : \Packetery\Nette\Utils\Html |
| 49 |
{ |
| 50 |
$items = []; |
| 51 |
foreach ($this->options as $key => $value) { |
| 52 |
$items[\is_array($value) ? $this->translate($key) : $key] = $this->translate($value); |
| 53 |
} |
| 54 |
return \Packetery\Nette\Forms\Helpers::createSelectBox($items, ['disabled:' => \is_array($this->disabled) ? $this->disabled : null] + $this->optionAttributes, $this->value)->addAttributes(parent::getControl()->attrs)->multiple(\true); |
| 55 |
} |
| 56 |
/** @return static */ |
| 57 |
public function addOptionAttributes(array $attributes) |
| 58 |
{ |
| 59 |
$this->optionAttributes = $attributes + $this->optionAttributes; |
| 60 |
return $this; |
| 61 |
} |
| 62 |
/** @return static */ |
| 63 |
public function setOptionAttribute(string $name, $value = \true) |
| 64 |
{ |
| 65 |
$this->optionAttributes[$name] = $value; |
| 66 |
return $this; |
| 67 |
} |
| 68 |
public function getOptionAttributes() : array |
| 69 |
{ |
| 70 |
return $this->optionAttributes; |
| 71 |
} |
| 72 |
} |
| 73 |
|