7

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?

asked Aug 28, 2017 at 16:26

3 Answers 3

4

@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.

answered Nov 1, 2017 at 6:16
2

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' => ' ',

answered Oct 11, 2017 at 14:52
1

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;
 }
}
answered Sep 28, 2017 at 12:48
1
  • 1
    The right way is to add caption to the select component <item name="caption" xsi:type="string" translate="true">Select one...</item> Commented Oct 2, 2017 at 13:02

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.