1

I have created a custom select attribute for products using InstallData, options of that attribute are shown using source model. It shows options correctly but when I add a Please select option with an empty value it shows Please Select option two times in dropdown. Please see the code below for both the cases.

InstallData.php

$eavSetup->addAttribute(
        \Magento\Catalog\Model\Product::ENTITY,
        'warranty_type',
        [
            'group' => 'Custom Options',
            'type' => 'varchar',
            'backend' => '',
            'label' => 'Warranty Type',
            'source' => 'VENDOR\MODULE\Model\Config\Source\Options\WarrantyTypeOptions',
            'input' => 'select',
            'visible' => true,
            'required' => true,
            'visible_on_front' => false
        ]
    );

WarrantyTypeOptions.php

class WarrantyTypeOptions extends \Magento\Eav\Model\Entity\Attribute\Source\AbstractSource{
/**
 * Return array of options as value-label pairs
 *
 * @return array
 */
public function getAllOptions()
{
    $options = [
        ['value' => 'Local', 'label' => __('Local')],
        ['value' => 'International', 'label' => __('International')],

    ];

    return $options;
}

}

This works fine and shows two options only:

<option data-title="Local" value="Local">Local</option>
<option data-title="International" value="International">International</option>

But when I add Please Select option with an empty value:

$options = [
        ['value' => '', 'label' => 'Please Select'],
        ['value' => 'Local', 'label' => __('Local')],
        ['value' => 'International', 'label' => __('International')],

    ];

This gives two Please Select options in dropdown:

<option value="">Please Select</option>
<option data-title="Please Select" value="">Please Select</option>
<option data-title="Local" value="Local">Local</option>
<option data-title="International" value="International">International</option>

Any suggestion how to correct it.

Thanks in advance.

0

I have also got the same issue and found that there this thing is going wrong. So as an alternative you can replace your options with this:

$options = [
    ['value' => ' ', 'label' => 'Please Select'],
    ['value' => 'Local', 'label' => __('Local')],
    ['value' => 'International', 'label' => __('International')],

];

In this way only one option will show.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy