Categories: How ToMagento 2

How to Create Dependent Dropdowns in Magento 2 Frontend Form

As a Magento 2 Store owner, you always need to collect various information from your potential customers using the form to provide quality service. In the 21st Century along with people, forms are getting smarter by using dependencies on various user inputs which helps to save tons of time and reduce efforts to fill online forms. This ultimately leads to the success rate of forms.

With dynamic dependent form fields, Store owner can easily ask further qualifying questions based on the user’s answers using various conditions. Basically, dependent forms dynamically show/hide or changes the value of form fields based on the user selections.
For example, if you want to list out products of a particular category, then we have to create category-products dropdown so that when users select a category, related products will be shown in dropdown option.

Here we’ve come up with the custom code in which whenever customer picks any option from drop-down another dropdown should be displayed with respective options based on the dropdown 1 selection. We have developed this functionality using Ajax code, which today we are likely to share with you guys on our blog.

Firstly, you need to add form to your phtml file with following code.

<div class="field frame_name required">
                           <label class="label" for="frame_name"><span><?php echo __('Option Name') ?></span></label>
                           <div class="control">
                                            <select name="frame_name" id="frame_name" title="<?php echo __(Option Name') ?>" class="input-text" data-validate="{required:true}">
                          <option value=""><?php echo __('Please Select Frame .') ?></option>
                              <option value="value1"><?php echo __('Frontend Option 1') ?></option>    
                          <option value="value2"><?php echo __('Frontend Option 2') ?></option>    
                          <option value="value3"><?php echo __('Frontend Option 3’) ?></option>    
                          <option value="value4"><?php echo __('Frontend Option 4') ?></option>    
                          <option value="value5"><?php echo __('Frontend Option 5') ?></option>    
                           </select>
                           </div>
            </div>
            <div class="field frame_color required">
                           <label class="label" for="frame_color">
<span><?php echo __('Option Title') ?></span>
</label>
                           <div class="control">
                           <select name="frame_color" id="frame_color" title="<?php echo __('Option Title') ?>" class="input-text" data-validate="{required:true}">
                              <option value=""><?php echo __('Please Select Option') ?></option>    
                           </select>
                           </div>
            </div>
 
<script>
   jQuery(document).on('change','#frame_name',function() {
              var param = 'frame='+jQuery('#frame_name').val();
              jQuery.ajax({
                              showLoader: true,
                              url: '<?php echo $block->getframeAction(); ?>',
                              data: param,
                              type: "GET",
                              dataType: 'json'
              }).done(function (data) {
                              jQuery('#frame_color').empty();
                              jQuery('#frame_color').append(data.value);
              });
    });
</script>

Once you have added the code to your file, you need to create block file “Index.php” at app\code\Vendor\Extension\Block\

<?php
namespace Vendor\Extension\Block;
 
class Index extends \Magento\Framework\View\Element\Template
{
    protected $_isScopePrivate;
    
    public function __construct(
            \Magento\Framework\View\Element\Template\Context $context,
            array $data = []
             )
             {
             parent::__construct($context, $data);
             $this->_isScopePrivate = true;
             }
 
    public function getframeAction()
             {
             return $this->getUrl('extension/extension/frame', ['_secure' => true]);
             }
}

Lastly, we need to create action using “ajax-handler.php” file that can handle all the ajax request comes from frontend form.
app\code\Vendor\Extension\Controller\Extension\

<?php
namespace Vendor\Extension\Controller\Extension;
 
class Frame extends \Magento\Framework\App\Action\Action
{
    protected $resultJsonFactory;
    
    protected $regionColFactory;
 
             public function __construct(
             \Magento\Framework\App\Action\Context $context,
             \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
             \Magento\Directory\Model\RegionFactory $regionColFactory)
    {       
             $this->regionColFactory             = $regionColFactory;
             $this->resultJsonFactory = $resultJsonFactory;
             parent::__construct($context);
             }
    
             public function execute()
             {
              $result = $this->resultJsonFactory->create();
             
              $html='<option selected="selected" value="">Please Select Option</option>';
             
             $frameName = $this->getRequest()->getParam('frame');
              if($frameName!='')
              {
                              switch ($frameName)
                              {
                                            case 'value1' :
                                                     $html.='<option value="Option 1">Title 1</option>';
                                                     $html.='<option value="Option 2">Title 2</option>';
                                                     break;
                                                              
                                            case 'value2' :
                                                     $html.='<option value="Option 1">Title 1</option>';
                                                     $html.='<option value="Option 2">Title 2</option>';
                                                     Break;

                                            // handle other switch case as per your requirements
                                                             
                              }    
              }
             
              return $result->setData(['success' => true,'value'=>$html]);
   }
}

And Tadaa, you are done with adding dependent dropdown options in your Magento 2 store frontend form. You can even add or change form elements based on your requirement of collecting various information.
Feel free to ask any question regarding this code, I would be glad to help you.
Let us know in comment section that how you have used this code and don’t forget to smash below stars.

Happy Coding!

Click to rate this post!
[Total: 6 Average: 4.3]
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.🏏

View Comments

Recent Posts

Magento 2: Add Quantity Increment and Decrement on Category Page

Hello Magento Friends, In this blog, we will discuss about adding quantity increment and decrement…

2 days ago

How to Integrate ChatGPT with Laravel Application?

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

5 days 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…

7 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…

7 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…

1 week 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…

1 week ago