Categories: How ToMagento 2

How to Implement Fields Dependency in Custom Admin Form of Magento 2

While surfing online, you probably have filled hundreds of forms whether it is related to signup, contact or anything. If you have noticed when you select one particular option it shows other relevant options to select from. Such options are known as Field Dependencies controls. It hides unnecessary fields until you don’t make a relational choice. Using such field dependencies in the form helps you to prevent bad user experience and collect all related information in less time.
While creating an extension from scratch many times it happens that you have so many configurations but some of them are dependable at that time, you have to create field dependencies.
For example, here we have used a dropdown field to show or hide dependable textbox. If the user selects “show” it shows the dependable textbox else it will gets hidden.
Once you create a basic form now inside your custom extension folder. After that, you have to add below code in your “form.php” file.
app\code\Vendor\Extension\Block\Adminhtml\Grid\Edit\Tab\Form.php

<?php
namespace Vendor\Extension\Block\Adminhtml\Grid\Edit\Tab;

class Form extends \Magento\Backend\Block\Widget\Form\Generic implements \Magento\Backend\Block\Widget\Tab\TabInterface
{
    protected function _prepareForm()
    {
        $form = $this->_formFactory->create();
        $fieldset = $form->addFieldset('base_fieldset', array('legend' => __('General')));
        $main = $fieldset->addField(
            "main",
            "select",
            [
                "label"     =>      __("Main"),
                "class"     =>      "required-entry",
                "name"      =>      "main",
                "values"    =>      [
                    ["value" => 0,"label" => __("Hide")],
                    ["value" => 1,"label" => __("Show")],
                ]
            ]
        );
        $sub = $fieldset->addField(
            "dependent_field",
            "text",
            [
                "label"     => __("Dependent Field"),
                "class"     => "required-entry",
                "required"  => true,
                "name"      => "dependent_field"
            ]
        );
        $this->setChild(
            'form_after',
            $this->getLayout()->createBlock('\Magento\Backend\Block\Widget\Form\Element\Dependence')
                ->addFieldMap($main->getHtmlId(), $main->getName())
                ->addFieldMap($sub->getHtmlId(), $sub->getName())
                ->addFieldDependence($sub->getName(), $main->getName(), 1)
        );


        $this->setForm($form);
        return parent::_prepareForm();   
    }
    public function getTabLabel()
    {
        return __('General');
    }
    public function getTabTitle()
    {
        return __('General');
    }
    public function canShowTab()
    {
        return true;
    }
    public function isHidden()
    {
        return false;
    }
}

That’s it. You are free to manipulate this code according to your need to show hide multiple form controls.

Lastly, if you found this blog helpful, don’t forget to share it with your colleagues and Magento Friends and Let us know if you are facing any issue while implementing this code.

Happy Fixing!

Click to rate this post!
[Total: 9 Average: 5]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate 🎖️ Certified Magento Developer👨‍💻. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.🏏

Recent Posts

How to Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

4 hours ago

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

2 days ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

2 days ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

3 days ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

4 days ago

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

6 days ago