Question

I need to add Country and State Dropdown in Magento 2 admin form. Please help me.

Was it helpful?

Solution

To add Country and State Dropdown in admin form, follow below steps:

In your form Block file:

Define variables:

protected $_regionFactory;
protected $_countryFactory;

In Construction:

public function __construct(
        ...
        \Magento\Directory\Model\RegionFactory $regionFactory,
        \Magento\Directory\Model\Config\Source\Country $countryFactory,
        ...
    ) {
        ...
        $this->_regionFactory = $regionFactory;
        $this->_countryFactory = $countryFactory;
        ...
    }

In initForm :

$countries = $this->_countryFactory->toOptionArray();

        $countryData = $fieldset->addField(
            'mycountry',
            'select',
            [
                'name' => 'mycountry',
                'data-form-part' => $this->getData('target_form'),
                'title' => __('Country'),
                'label' => __('Country'),
                'value' => $partner['mycountry'],
                'values' => $countries
            ]
        );

        $regionCollection = $this->_regionFactory->create()->getCollection()->addCountryFilter($partner['mycountry']);
        $regions = $regionCollection->toOptionArray();

        $fieldset->addField(
            'mystate',
            'select',
            [
                'name' => 'mystate',
                'data-form-part' => $this->getData('target_form'),
                'title' => __('State'),
                'label' => __('State'),
                'values' =>  $regions,
                'value' => $partner['mystate'],
            ]
        );
        $countryData->setAfterElementHtml("   
            <script type=\"text/javascript\">
                    require([
                    'jquery',
                    'mage/template',
                    'jquery/ui',
                    'mage/translate'
                ],
                function($, mageTemplate) {
                   $('#edit_form').on('change', '#country_id', function(event){
                        $.ajax({
                               url : '". $this->getUrl('test/*/regionlist') . "country/' +  $('#country_id').val(),
                                type: 'get',
                                dataType: 'json',
                               showLoader:true,
                               success: function(data){
                                    $('#region_id').empty();
                                    $('#region_id').append(data.htmlconent);
                               }
                            });
                   })
                }

            );
            </script>"
        );

Here $partner is the variable which contain all form data.

OTHER TIPS

Can you use below code

<?php
/**
 * @var \Magento\Directory\Model\Config\Source\Country
 */
protected $_country;

/**
 * @var \Magento\Directory\Model\RegionFactory
 */
protected $_regionFactory;

// ... add them in __construct

// ...

// Add next changes in the _prepareForm method

$countries = $this->_country->toOptionArray(false, 'US');
$regionCollection = $this->_regionFactory->create()->getCollection()->addCountryFilter(
    $formData['country_id']
);
$regions = $regionCollection->toOptionArray();

$fieldset->addField(
    'country_id',
    'select',
    ['name' => 'country_id', 'label' => __('Country'), 'required' => true, 'values' => $countries]
);

$fieldset->addField(
    'region_id',
    'select',
    ['name' => 'region_id', 'label' => __('State'), 'values' => $regions]
);


$this->setChild(
    'form_after',
    $this->getLayout()->createBlock('Magento\Framework\View\Element\Template')->setTemplate('Vendor_Module::js.phtml')
);
?>

> Vendor_Module::js.phtml

<script>
    require([
        "jquery",
        "mage/adminhtml/form"
    ], function ($) {

        var updater = new RegionUpdater($('[name=country_id]')[0], $('[name=region]')[0], $('[name=region_id]')[0],
            <?php echo $this->helper('Magento\Directory\Helper\Data')->getRegionJson() ?>,
            'hide'
        );
        updater.disableRegionValidation();
        window.updater = updater;
    });
</script>
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top