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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
<?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!