Understanding that each business is different with unique requirements. Each store owner has his own needs for their web stores in order to provide better shopping experience. When a store is created for some specific countries or location and when admin needs to have some custom form, he needs to have it with selection options rather than text boxes in order to minimize users’ efforts to fill in and maximize their experience.While working on our client’s Magento 2 store, we required to have two selection boxes; one for countries and other for states selection. As the selection options are generally presented with dropdown, we choose to add 2 dropdowns to serve the purpose. To Create Country and State Dropdown in Magento 2 Custom Frontend Form, we implemented a custom code which I’m sharing with you today.

First create a file “index.php” at app\code\local\Vendor\Extension\Block with below code.

Now, you need to create another file at app\code\local\Vendor\Extension\view\frontend\layout\ with following code and rename it as “extension_extension_index.xml

Now create “index.phtml” with following code at app\code\local\Vendor\Extension\view\frontend\templates\extension

Lastly, you need to create “Country.php” in your extension folder at app\code\local\Vendor\Extension\Controller\Extension\ with following code.

Adding country and state dropdowns in Magento 2 custom form is not rocket science, it’s as easy pie! Simply modify above code according to your custom fields and options, paste in your custom form and voila, you are done! I hope the code has enough served your purpose to implement country and state dropdown in Magento 2.
Let me know how did you customize the code and where have you used it. Also, tell me if you stuck somewhere and need help.

Don’t forget to flash out the 5 stars below if you like the tutorial.
Happy Coding!

CityRegion Manager

Click to rate this post!
[Total: 21 Average: 4.6]