Magento – Create custom dropdown for custom module in magento product edit section

custommagento2PHPproduct

I have created my own custom module for "Critic Expert" feature. I want to assign a critic expert with each product so I have to add my custom dropdown with each product.

How would I can show the dropdown with my custom module values and save it along with product in admin section.

Please find attached screenshot for more details.

enter image description here

Best Answer

I have created Small module. It will help you.

Create module files which are listed below.

app/code/Kunj/Critic/etc/module.xml:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Kunj_Critic" setup_version="2.0.0"></module>
</config>

app/code/Kunj/Critic/Model/Critic/Options.php

<?php

namespace Kunj\Critic\Model\Critic;


class Options implements \Magento\Framework\Option\ArrayInterface
{
    public function toOptionArray()
    {
        return [
            [
                'value'=>1,
                'label'=>"My Option"
            ],
            [
                'value'=>2,
                'label'=>"My Option 2"
            ],
            [
                'value'=>3,
                'label'=>"My Option 3"
            ],
            [
                'value'=>4,
                'label'=>"My Option 4"
            ],
            [
                'value'=>5,
                'label'=>"My Option 5"
            ]
        ];
    }
}

app/code/Kunj/Critic/view/adminhtml/ui_component/product_form.xml

<?xml version="1.0" encoding="UTF-8"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <fieldset name="product-details">
        <field name="critic_lists" sortOrder="300" formElement="select">
            <argument name="data" xsi:type="array">
                <item name="options" xsi:type="object">Kunj\Critic\Model\Critic\Options</item>
                <item name="config" xsi:type="array">
                    <item name="source" xsi:type="string">block</item>
                </item>
            </argument>
            <settings>
                <validation>
                    <rule name="required-entry" xsi:type="boolean">true</rule>
                </validation>
                <dataType>select</dataType>
                <label translate="true">Critic Lists</label>
                <dataScope>critic_lists</dataScope>
            </settings>
        </field>
    </fieldset>
</form>

app/code/Kunj/Critic/registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Kunj_Critic',
    __DIR__
);

After create module run :

php bin/magento setup:upgrade