0

I want to add country and state drop down in custom admin form.

How can I do that ?

1 Answer 1

1

Try This Code into your Form

In UI- Component

<field name="country_id">
    <argument name="data" xsi:type="array">
        <item name="options" xsi:type="object">Magento\Directory\Model\Config\Source\Country</item>
        <item name="config" xsi:type="array">
            <item name="dataType" xsi:type="string">text</item>
            <item name="label" xsi:type="string" translate="true">Country</item>
            <item name="formElement" xsi:type="string">select</item>
            <item name="source" xsi:type="string">store</item>
            <item name="component" xsi:type="string">Magento_Ui/js/form/element/country</item>
            <item name="validation" xsi:type="array">
                <item name="required-entry" xsi:type="boolean">true</item>
            </item>
        </item>
    </argument>
</field>
<field name="region">
    <argument name="data" xsi:type="array">
        <item name="options" xsi:type="object">Magento\Directory\Model\ResourceModel\Region\Collection</item>
        <item name="config" xsi:type="array">
            <item name="dataType" xsi:type="string">text</item>
            <item name="label" xsi:type="string" translate="true">State/Region</item>
            <item name="formElement" xsi:type="string">select</item>
            <item name="source" xsi:type="string">store</item>
            <item name="sortOrder" xsi:type="number">20</item>
            <item name="customEntry" xsi:type="string">region</item>
            <item name="validation" xsi:type="array">
                <item name="required-entry" xsi:type="boolean">true</item>
            </item>
            <item name="filterBy" xsi:type="array">
                <item name="target" xsi:type="string">${ $.provider }:${ $.parentScope }.country_id</item>
                <item name="field" xsi:type="string">country_id</item>
            </item>
        </item>
    </argument>
</field>

Using Block

class Form extends \Magento\Backend\Block\Widget\Form\Generic
{
    
    protected $_systemStore;

    protected $_countryFactory;

    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Framework\Registry $registry,
        \Magento\Framework\Data\FormFactory $formFactory,
        \Magento\Cms\Model\Wysiwyg\Config $wysiwygConfig,
        \Magento\Directory\Model\Config\Source\Country $countryFactory,
        \Magento\Store\Model\System\Store $systemStore,
        array $data = []
    ) {
        $this->_systemStore = $systemStore;
        $this->_countryFactory = $countryFactory;
        $this->_wysiwygConfig = $wysiwygConfig;
        parent::__construct($context, $registry, $formFactory, $data);
    }

    protected function _prepareForm()
    {   
        $regioncode = $this->getRequest()->getParam('region');    

        $isElementDisabled = false;

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

        $dateFormat = $this->_localeDate->getDateFormat(\IntlDateFormatter::SHORT);

        $model = $this->_coreRegistry->registry('row_data');

            if (!$model->getId()) 
            {
                $model->setData('is_active', $isElementDisabled ? '0' : '1');
            }

        $form = $this->_formFactory->create(
            ['data' => [
                            'id' => 'edit_form',
                            'enctype' => 'multipart/form-data',
                            'action' => $this->getData('action'),
                            'method' => 'post'
                        ]
            ]
        );

        $form->setHtmlIdPrefix('storelocation_');

        if ($model->getId()) {
            $fieldset = $form->addFieldset(
                'base_fieldset',
                ['legend' => __('Edit Store Location General Information'), 'class' => 'fieldset-wide']
            );
            $fieldset->addField('id', 'hidden', ['name' => 'id']);

            $region_value = $model->getData('region');

        } else {
            $fieldset = $form->addFieldset(
                'base_fieldset',
                ['legend' => __('Location General Information'), 'class' => 'fieldset-wide']
            );

            $region_value = NULL;
        }

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

        $country =  $fieldset->addField(
            'country',
            'select',
            [
                'name' => 'country',
                'label' => __('Country'),
                'id' => 'country',
                'title' => __('Country'),
                'class' => 'required-entry',
                'values' => $optionsc,
                'required'  => true,
            ]
        );


        $fieldset->addField(
            'region',
            'select',
            [
                'name' => 'region',
                'label' => __('Region'),
                'id' => 'region',
                'title' => __('Region'),
                'class' => 'required-entry',
                'values' =>['--Please Select Country--'],
                'required'  => true,
            ]
        );
  
    /* for add java script for country and region select */

        $country->setAfterElementHtml("   
    
    <script type=\"text/javascript\">
            require(['jquery', 'jquery/ui'],function($) {

                    // on intial check whether country code exit or not 
                        
                   $(window).on('load', function() {

                    var country = $('#storelocation_country').val();
                    //var region = $('#storelocation_region').val();

                    var region = '".$region_value."';



                        //alert('region '+region+' country '+country);

                        $.ajax({
                               url : '". $this->getUrl('*/*/regionlist') . "country/' + $('#storelocation_country').val()+'/region/'+region,
                               type: 'get',
                               dataType: 'json',
                               showLoader:true,
                               success: function(data){
                                    $('#storelocation_region').empty();
                                    $('#storelocation_region').append(data.htmlconent);
                               }
                            });



                    });   

                    // onchange country this function called 

                   $(document).on('change', '#storelocation_country', function(event){

                    var country = $('#storelocation_country').val();

                    //alert(country);

                        $.ajax({
                               url : '". $this->getUrl('*/*/regionlist') . "country/' + $('#storelocation_country').val(),
                               type: 'get',
                               dataType: 'json',
                               showLoader:true,
                               success: function(data){
                                    $('#storelocation_region').empty();
                                    $('#storelocation_region').append(data.htmlconent);
                               }
                            });
                   })
                }

            );
            </script>"
        );

        $form->setValues($model->getData());
        $form->setUseContainer(true);
        $this->setForm($form);

        return parent::_prepareForm();
    }
}

Add This File which get your region accourding to country name

<?php

namespace VendoreName\ModuleName\Controller\Adminhtml\YourAdminCoontroller;

class Regionlist extends \Magento\Framework\App\Action\Action
{

    protected $resultPageFactory;
    protected $_countryFactory;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Directory\Model\CountryFactory $countryFactory,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory
    )
    {
        $this->_countryFactory = $countryFactory;
        $this->resultPageFactory = $resultPageFactory;
        parent::__construct($context);
    }

    public function execute()
    {


        $countrycode = $this->getRequest()->getParam('country');

        $regioncode = $this->getRequest()->getParam('region');

        if($regioncode == NULL){
            $regioncode='';
        }

        $selected = '';

        $state = "<option value=''>--Please Select--</option>";
        if ($countrycode != '') {
            $statearray =$this->_countryFactory->create()->setId(
                    $countrycode
                )->getLoadedRegionCollection()->toOptionArray();
            foreach ($statearray as $_state) {
                if($_state['value']){

                        if($regioncode == $_state['label']) { $selected = 'selected'; } else{  $selected = ''; }

                    $state .= "<option value='".$_state['label']."'  ".$selected." >" .$_state['label']. "</option>";
            }
           }
        }
        $result['htmlconent']=$state;
         $this->getResponse()->representJson(
            $this->_objectManager->get('Magento\Framework\Json\Helper\Data')->jsonEncode($result)
        );
    }
  }
1
  • working fine but when there is no state and textbox value saved it is not showing saved value in form textbox
    – M2 Dev
    Commented Jul 25, 2022 at 9:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.