Reading list Switch to dark mode

    How to create dependable field in admin custom form in Magento2

    Updated 26 March 2024

    Here we will learn that how to add dependable field in admin custom form in Magento2. Magento already provided all input fields which we use at the time of form creation like text, select , multiselect etc.

    Sometimes we have to need dependable field which are dependent to other input field (select type) value. We are going to explain how to create dependable fields.

    We will not explain here basic form creation. If you beginner then you can check this blog .

    After successfully created basic form .Now you can add following code into Form.php In App/Code/Webkul/Grid/Block/Adminhtml/Grid/Edit to add dependable field.

    $action = $fieldset->addField(
        "main_field",
        "select",
        [
            "label"     =>      __("Main Field"),
            "class"     =>      "required-entry",
            "name"      =>      "main_field",
            "values"    =>      [
                ["value" => 0,"label" => __("Do Nothing")],
                ["value" => 1,"label" => __("Display Field")],
            ]
        ]
    );
    
    $anotherField = $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($action->getHtmlId(), $action->getName())
        ->addFieldMap($anotherField->getHtmlId(), $anotherField->getName())
        ->addFieldDependence($anotherField->getName(), $action->getName(), 1)
    );

    In first section we create main field select the value of this field display dependent field.Second section create dependent field.In third we define which field display after select main field and also define the value.

    Searching for an experienced
    Magento 2 Company ?
    Find out More

    You can check screen-shot.In first screen-shot initial state of form and second screen-shot show dependent field after select main field value.

    initial state of form
    after select another option

    I hope this blog will help you to create dependent field in your custom form.If you get any issue or query then you can comment below.Thanks

    . . .

    Leave a Comment

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


    2 comments

  • Swaleha
    • abhishek (Moderator)
  • Back to Top

    Message Sent!

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

    Back to Home