How To Use Dependency Multiple Field In Magento 2 Admin Form

Magento 2 platform gets better every day to improve the user experience. If the CMS falls short, the developers have the flexibility to customize the default features.

Using dependency multiple fields is one such thing you can implement to improve the user experience, collect relevant and accurate data from the users, and hide the unnecessary fields in the form.

For example,

Method To Use Dependency Multiple Field In Magento 2 Admin

You can also use dependency multiple field in Magento 2 admin form for custom requirements or custom forms. Use the below solution to create a dependable field in admin custom form in Magento2:

Method To Use Dependency Multiple Field In Magento 2 Admin Form:

<?php

namespace Vendor\Extension\Block\Adminhtml\Extension\Edit\Tab;

use Magento\Backend\Block\Template\Context;
use Magento\Framework\Data\FormFactory;
use Magento\Framework\Registry;
use Magento\Store\Model\System\Store;
use Magento\Backend\Block\Widget\Form\Generic;
use Magento\Backend\Block\Widget\Tab\TabInterface;
use Magento\Catalog\Model\ProductFactory;

class Detail extends Generic implements TabInterface
{
    protected $_systemStore;
    protected $productFactory;

    public function __construct(
        Context $context,
        Registry $registry,
        FormFactory $formFactory,
        ProductFactory $productFactory,
        Store $systemStore,
        array $data = []
    )
    {
        $this->_systemStore = $systemStore;
        $this->productFactory = $productFactory;
        parent::__construct($context, $registry, $formFactory, $data);
    }

    public function getTabLabel()
    {
        return __('Options');
    }

    public function getTabTitle()
    {
        return __('Options');
    }

    public function canShowTab()
    {
        return true;
    }

    public function isHidden()
    {
        return false;
    }

    protected function _prepareForm()
    {
        try {
            $model = $this->_coreRegistry->registry('current_Extension_option');

            $form = $this->_formFactory->create();
            $form->setHtmlIdPrefix('page_');

            $fieldset = $form->addFieldset('base_fieldset', ['legend' => __('Settings')]);

            if ($model->getId()) {
                $fieldset->addField('id', 'hidden', ['name' => 'id']);
            }

            

            $repeatPayment = $fieldset->addField(
                'repeat_payment',
                'select',
                [
                    'name' => 'repeat_payment',
                    'label' => __('Repeat Payments'),
                    'title' => __('Repeat Payments'),
                    'required' => true,
                    'options' => ['1' => __('Daily'),
                        '2' => __('Weekly'),
                        '3' => __('Monthly'),
                        '4' => __('Every...'),
                    ]
                ]
            );

            $frequeancyOption = $fieldset->addField(
                'frequancy_option',
                'select',
                [
                    'name' => 'frequancy_option',
                    'label' => __(''),
                    'title' => __(''),
                    'required' => true,
                    'options' => $this->frequeancyOption()
                ]
            );

            

            $form->setValues($model->getData());
            $this->setForm($form);

            $this->setChild(
                'form_after',
                $this->getLayout()->createBlock('\Magento\Backend\Block\Widget\Form\Element\Dependence')
                    ->addFieldMap($repeatPayment->getHtmlId(), $repeatPayment->getName())
                    ->addFieldMap($frequeancyOption->getHtmlId(), $frequeancyOption->getName())
                    ->addFieldDependence($frequeancyOption->getName(), $repeatPayment->getName(), 4)
            );

        } catch (\Exception $e) {
            \Magento\Framework\App\ObjectManager::getInstance()->get('Psr\Log\LoggerInterface')->info($e->getMessage());
        }
        return parent::_prepareForm();
    }

    protected function _isAllowedAction($resourceId)
    {
        return $this->_authorization->isAllowed($resourceId);
    }

    protected function frequeancyOption()
    {
        $opt = ['1' => __('1st'),
            '2' => __('2nd'),
            '3' => __('3rd'),
        ];

        for ($i = 4; $i <= 365; $i++) {
            $opt[$i] = $i."th";
        }

        return $opt;
    }
}

That’s it.

Feel free to share the solution with fellow developers via social media.

Thanks.

Sanjay Jethva

Article by

Sanjay Jethva

Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe. His passion for Magento 2 and Shopify solutions has made him a trusted source for...