I have a product attribute dropdown select box that I populate via a source model.
The population works fine, but I want the first option in the list to be "Select one...". I've used the following code:
$options[] = array(
'label' => 'Select one...',
'value' => '',
);
But the result is as follows:
Duplicated empty item in select attribute
With the rendered HTML:
<select>
<option value="">Select one...</option>
<option data-title="Select one..." value="">Select one...</option>
What am I doing wrong?
3 Answers 3
@awarche's answer works:
You'll need to add a caption to your UI component field config:
<item name="caption" xsi:type="string" translate="true">Select one...</item>
I don't think an empty "Please select..." value belongs in a source model.
So not sure how to do this with a label but if you just want a empty select you need to follow the core example and use an empty string:
vendor/magento/module-eav/Model/Entity/Attribute/Source/Table.php
/**
* @param array $options
* @return array
*/
private function addEmptyOption(array $options)
{
array_unshift($options, ['label' => $this->getAttribute()->getIsRequired() ? '' : ' ', 'value' => '']);
return $options;
}
i.e 'label' => ' ',
It works with label ' ' and value ''.
Maybe the select field component has some restrictions or rather a bug.
If you add the select attribute's values with InstallData or UpgradeData using the 'source' property, you also need to include a space for the empty option's label.
<?php
declare(strict_types=1);
namespace <yournamespace>\<yourmodule>\Helper;
use Magento\Eav\Model\Entity\Attribute\Source\AbstractSource;
class <YourProduct>ProductAttribute extends AbstractSource
{
public const DEMO_ATTR = "demo_attr";
public function getAllOptions(): ?array
{
if ($this->_options === null) {
$this->_options = [
['label' => ' ', 'value' => ''],
['label' => 'First value', 'value' => 1],
];
}
return $this->_options;
}
}
-
1The right way is to add caption to the select component
<item name="caption" xsi:type="string" translate="true">Select one...</item>awarche– awarche2017年10月02日 13:02:30 +00:00Commented Oct 2, 2017 at 13:02
Explore related questions
See similar questions with these tags.