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.
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.
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
2 comments
Hello Swaleha,
You can add same field in different list by apply join on that new collection .
for this you can follow this https://webkul.com/blog/join-two-table-and-create-grid-in-admin-section-using-ui-component-in-magento2/
Thanks