How to Add a Drop Down in Magento 2 Admin Form

In this code snippet, we will see how to add a dropdown with custom options in Magento 2 Admin Form. We assume that you have already created a Magento 2 admin module.

Add a Drop Down in Magento 2 Admin Form

In your form file codextblog_demo_form.xml inside app/code/Codextblog/Demo/view/adminhtml/ui_component add below code.

<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
	<fieldset name="general">
		<field name="category" formElement="select" sortOrder="20">
            <argument name="data" xsi:type="array">
                <item name="options" xsi:type="object">Codextblog\Demo\Model\Source\Category</item>
                <item name="config" xsi:type="array">
                    <item name="source" xsi:type="string">Demo</item>
                </item>
            </argument>
            <settings>
                <dataType>text</dataType>
                <label translate="true">Blog Category</label>
                <dataScope>category</dataScope>
                <validation>
                    <rule name="required-entry" xsi:type="boolean">true</rule>
                </validation>
            </settings>
        </field>
	</fieldset>
</form>

To render options, we have specified PHP class in line no 5. Now add a Category.php file under Codextblog/Demo/Model/Source directory. Add below code in that file.

<?php
namespace Codextblog\Demo\Model\Source;

use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory;
use Magento\Framework\Data\OptionSourceInterface;

class Category implements OptionSourceInterface
{
    /**
     * @var CollectionFactory
     */
    protected $collectionFactory;

    public function __construct(
        CollectionFactory $collectionFactory
    ) {
        $this->collectionFactory = $collectionFactory;
    }

    public function toOptionArray()
    {
        $options[] = ['label' => '-- Please Select --', 'value' => ''];
        $collection = $this->collectionFactory->create()
            ->addAttributeToSelect('*')
            ->addAttributeToFilter('is_active', '1');

        foreach ($collection as $category) {
            $options[] = [
                'label' => $category->getName(),
                'value' => $category->getId(),
            ];
        }

        return $options;
    }
}

If everything works well, then you will see a dropdown with categories name as an option. Cheers!!