Back to Top

Get dropdown options from the dependent dropdown

Updated 26 May 2023

In this blog, we are going to learn how we can get dropdown options from the dependent dropdown option in the admin form using the Ui component.

Here is the example we are going to achieve:-

We have two dropdowns in the custom module. 1st is for Car Maker and 2nd for the Car Model. The Car Model dropdown is dependent on the Car Maker dropdown.

All options will be displayed in the Car Model dropdown on selecting the dependent Car Maker dropdown option.

Let’s start the code, How can achieve the same:-

Searching for an experienced
Magento 2 Company ?
Find out More

Step 1:- Create a layout file with the name mobikulcore_year_edit.xml file inside the app/code/Vendor/Module/view/adminhtml/layout/ directory.

For defining the page layout and calling ui component.

<!--
/**
 * Module Software.
 *
 * @category  Webkul
 * @package   Webkul_Module
 * @author    Webkul
 * @copyright Copyright (c) Webkul Software Private Limited (https://vendor.com)
 * @license   https://store.webkul.com/license.html
 */
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
    <update handle="styles"/>
    <body>
        <referenceContainer name="content">
            <uiComponent name="mobikulcore_year_form"/>
        </referenceContainer>
    </body>
</page>

Step 2: Create a UI component file with the name mobikulcore_year_form.xml file inside the app/code/Vendor/Module/view/adminhtml/ui_component/ directory.

For defining the dropdown fields in the UI component.

<?xml version="1.0" encoding="UTF-8"?>
<!--
/**
 * Module Software.
 *
 * @category  Webkul
 * @package   Webkul_Module
 * @author    Webkul
 * @copyright Copyright (c) Webkul Software Private Limited (https://vendor.com)
 * @license   https://store.webkul.com/license.html
 */
-->
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <argument name="data" xsi:type="array">
        <item name="js_config" xsi:type="array">
            <item name="provider" xsi:type="string">mobikulcore_year_form.year_list_data_source</item>
            <item name="deps" xsi:type="string">mobikulcore_year_form.year_list_data_source</item>
        </item>
        <item name="label" xsi:type="string" translate="true">Sample Form</item>
        <item name="layout" xsi:type="array">
            <item name="type" xsi:type="string">tabs</item>
        </item>

        <item name="buttons" xsi:type="array">
            <item name="save" xsi:type="string">Vendor\Module\Block\Adminhtml\Year\Edit\SaveButton</item>
        </item>
    </argument>

    <dataSource name="year_list_data_source">
        <argument name="dataProvider" xsi:type="configurableObject">
            <argument name="class" xsi:type="string">Vendor\Module\Model\Year\DataProvider</argument>
            <argument name="name" xsi:type="string">year_list_data_source</argument>
            <argument name="primaryFieldName" xsi:type="string">entity_id</argument>
            <argument name="requestFieldName" xsi:type="string">id</argument>
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="submit_url" xsi:type="url" path="*/*/save"/>
                </item>
            </argument>
        </argument>
        <argument name="data" xsi:type="array">
            <item name="js_config" xsi:type="array">
                <item name="component" xsi:type="string">Magento_Ui/js/form/provider</item>
            </item>
        </argument>
    </dataSource>

    <fieldset name="year">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="label" xsi:type="string" translate="true">Year</item>
            </item>
        </argument>
        <field name="car_maker_id">
            <argument name="data" xsi:type="array">
                <item name="options" xsi:type="object">Vendor\Module\Model\Config\Source\CarMaker</item>
                <item name="config" xsi:type="array">                    
                    <item name="sortOrder" xsi:type="number">20</item>
                    <item name="dataType" xsi:type="string">text</item>
                    <item name="component" xsi:type="string">Vendor_Module/js/form/element/CarMaker</item>
                    <item name="formElement" xsi:type="string">select</item>
                    <item name="label" xsi:type="string" translate="true">Car Maker</item>
                    <item name="source" xsi:type="string">category</item>
                    <item name="validation" xsi:type="array">
                        <item name="required-entry" xsi:type="boolean">true</item>
                    </item>
                </item>
            </argument>
        </field>
        
        <field name="model_line_id">
            <argument name="data" xsi:type="array">
                <item name="options" xsi:type="object">Module\Module\Model\Config\Source\ModelLine</item>
                <item name="config" xsi:type="array">                    
                    <item name="sortOrder" xsi:type="number">30</item>
                    <item name="dataType" xsi:type="string">text</item>
                    <item name="formElement" xsi:type="string">select</item>
                    <item name="label" xsi:type="string" translate="true">Model</item>
                    <item name="source" xsi:type="string">category</item>
                    <item name="validation" xsi:type="array">
                        <item name="required-entry" xsi:type="boolean">true</item>
                    </item>
                </item>
            </argument>
        </field>
    </fieldset>
</form>

Step 3: Create a CarMaker source file for showing all options in the car maker dropdown with the name CarMaker.php inside the app/code/Vendor/Module/Model/Config/Source directory.

For displaying all the options for Car Maker dropdown.

<?php
/**
 * Module Software.
 *
 * @category  Webkul
 * @package   Webkul_Module
 * @author    Webkul
 * @copyright Copyright (c) Webkul Software Private Limited (https://vendor.com)
 * @license   https://store.webkul.com/license.html
 */

namespace Vendor\Module\Model\Config\Source;
use Magento\Framework\Option\ArrayInterface;

class CarMaker implements ArrayInterface
{


    /**
     * __construct
     *
     * @param \Magento\Config\Model\Config\Source\Locale\Timezone $timezone
     */
    public function __construct(
        \Vendor\Module\Model\ResourceModel\CarMaker\Collection $carMakerCollection
    ) {
        $this->carMakerCollection = $carMakerCollection;
    }
    
    public function toOptionArray()
        {
            $options = [];
            foreach($this->carMakerCollection as $carMaker){
                $option = [];
                $option['value'] = $carMaker->getId();
                $option['label'] = $carMaker->getLabel();
                $options[]  = $option;

            }
            
            return $options;
        }
}

Step 4: Create a js component file with the name CarMaker.js file inside the app/code/Vendor/Module/view/adminhtml/web/js/form/element/ directory.

For the js event, get Car Model options by selecting the Car Maker dropdown.

/**
 * Module Software.
 *
 * @category  Webkul
 * @package   Webkul_Module
 * @author    Webkul
 * @copyright Copyright (c) Webkul Software Private Limited (https://vendor.com)
 * @license   https://store.webkul.com/license.html
 */
define([
    'jquery',
    'Magento_Ui/js/form/element/select',
    'mage/url'
], function ($, Select,url) {
    'use strict';
    
    return Select.extend({
        
        defaults: {
            customName: '${ $.parentName }.${ $.index }_input'
        },
        /**
         * Change currently selected option
         *
         * @param {String} id
         */
        onUpdate: function(value){
            this.ajax(value);
        },
        ajax: function(value){
            $.ajax({
                url: window.ajaxUrl+'/mobikulcore/year/ajax/',
                showLoader: true,
                data: {form_key: window.FORM_KEY, 'car_maker_id':value},
                type: "POST",
                dataType : 'json',
                success: function(result){
                
                    $('select[name="year[model_line_id]"]')
                    .find('option')
                    .remove()
                    .end();
              
                    $('select[name="year[model_line_id]"]')
                    .append($('<option>', {
                        value: "",
                        text: "Select Item"
                    })); 

                    result.forEach(function(item) {
                        
                        $('select[name="year[model_line_id]"]')
                        .append($('<option>', {
                            value: item.entity_id,
                            text: item.label
                        }));        
                    });
                   
                }
            });
        }
    });
});

Step 5: Now, create a controller file for Ajax request to get the Car Model date using Car Maker with the name Ajax.php file inside the app/code/Vendor/Module/Controller/Year/ directory.

For Ajax request to get all Car model options by selecting Car Maker.

<?php
/**
 * Module Software.
 *
 * @category  Webkul
 * @package   Webkul_Module
 * @author    Webkul
 * @copyright Copyright (c) Webkul Software Private Limited (https://vendor.com)
 * @license   https://store.webkul.com/license.html
 */
namespace Vendor\Module\Controller\Year;

class Ajax extends \Magento\Framework\App\Action\Action
{
    protected $resultPageFactory = false;

	public function __construct(
		\Magento\Framework\App\Action\Context $context,
		\Magento\Framework\Controller\Result\JsonFactory $jsonFactory,
		\Vendor\Module\Model\ResourceModel\ModelLine\CollectionFactory $modelCollectionFactory,
		\Vendor\Module\Model\ResourceModel\Year\CollectionFactory $yearCollectionFactory,
		\Vendor\Module\Model\ResourceModel\Modification\CollectionFactory $modificationCollectionFactory
	)
	{
		parent::__construct($context);
		$this->jsonFactory = $jsonFactory;
		$this->modelCollectionFactory = $modelCollectionFactory;
		$this->yearCollectionFactory = $yearCollectionFactory;
		$this->modificationCollectionFactory = $modificationCollectionFactory;
	}

	public function execute()
	{
		$formData = $this->getRequest()->getParams('formData');

		if($formData['type'] == "carMaker"){
			$modelLine = $this->modelCollectionFactory->create();
			$modelLine->addFieldToFilter("car_maker_id",$formData['id']); 
			$resultJson = $this->jsonFactory->create();

        return $resultJson->setData($modelLine->getData());
		}
		$resultJson = $this->jsonFactory->create();

		return $resultJson->setData([]);

		
	}
	   
}

Now, look into the first image in which Car Maker dropdown options are displayed in the form.

car-maker-dropdown-ss

And in the last image in which, As you can see all options are displayed in the Car Model dropdown options mapped with the selected Car Maker.

car-model-dropdown-ss

Hope this will be helpful.

Thanks ­čÖé

You can see other blogs as well:-

Add Custom Product Attributes

Add Custom Customer Group

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home