diff --git a/src/FormElement/SelectElement.php b/src/FormElement/SelectElement.php index a6677f30..77b2ba78 100644 --- a/src/FormElement/SelectElement.php +++ b/src/FormElement/SelectElement.php @@ -4,12 +4,15 @@ use Closure; use ipl\Html\Attributes; +use ipl\Html\Common\MultipleAttribute; use ipl\Html\Html; use ipl\Html\HtmlElement; use ipl\Validator\DeferredInArrayValidator; class SelectElement extends BaseFormElement { + use MultipleAttribute; + protected $tag = 'select'; /** @var SelectOption[] */ @@ -24,32 +27,6 @@ class SelectElement extends BaseFormElement /** @var array|string Array when the attribute `multiple` is set to true, string otherwise */ protected $value; - /** @var bool Whether the attribute `multiple` is set to true */ - protected $isMultiSelect; - - public function __construct($name, $attributes = null) - { - if (is_array($attributes)) { // because attributes can be in any order - $this->isMultiSelect = in_array('multiple', $attributes) && $attributes['multiple'] === true; - } elseif ($attributes instanceof Attributes) { - $this->isMultiSelect = $attributes->get('multiple')->getValue() === true; - } - - $this->getAttributes()->registerAttributeCallback( - 'options', - null, - [$this, 'setOptions'] - ); - // ZF1 compatibility: - $this->getAttributes()->registerAttributeCallback( - 'multiOptions', - null, - [$this, 'setOptions'] - ); - - parent::__construct($name, $attributes); - } - public function getValueAttribute() { // select elements don't have a value attribute @@ -58,7 +35,7 @@ public function getValueAttribute() public function getNameAttribute() { - if ($this->isMultiSelect) { + if ($this->isMultiple()) { return $this->getName() . '[]'; } @@ -69,11 +46,7 @@ public function getValue() { $value = parent::getValue(); - if ($this->isMultiSelect) { - return (array) $value; - } - - return $value; + return $this->isMultiple() ? (array) $value : $value; } /** @@ -212,7 +185,7 @@ protected function makeOption($value, $label) */ protected function isSelectedOption($optionValue): bool { - if ($this->isMultiSelect) { + if ($this->isMultiple()) { return in_array($optionValue, $this->getValue(), ! is_int($optionValue)); } @@ -227,4 +200,17 @@ protected function assemble() { $this->addHtml(...array_values($this->optionContent)); } + + protected function registerAttributeCallbacks(Attributes $attributes) + { + parent::registerAttributeCallbacks($attributes); + + $attributes->registerAttributeCallback( + 'options', + null, + [$this, 'setOptions'] + ); + + $this->registerMultipleAttributeCallback($attributes); + } }