0

I want to add country and State field at the backend in creating customer under the Account Information tab.

enter image description here

Based on the Country selected the State should filter in the dropdown.

enter image description here

Any help would be appreciated.

0

in admin form block in _prepareForm() add country and region

that is

in __construct() add country config source

protected $_countryFactory;

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

and in _prepareForm()

     protected function _prepareForm()
        {
    .
    .
    .
    .
    .
    old field 
    .
    .
    .
    .
    $optionsc=$this->_countryFactory->toOptionArray();
            $country = $fieldset->addField(
                'country_id',
                'select',
                [
                    'name' => 'country_id',
                    'label' => __('Country'),
                    'title' => __('Country'),
               // 'onchange' => 'getstate(this)',
                    'values' => $optionsc,
                ]
            );
            //$optionsc=$this->_countryFactory->toOptionArray();
            $fieldset->addField(
                'region_id',
                'select',
                [
                    'name' => 'region_id',
                    'label' => __('Region'),
                    'title' => __('Region'),
                    'values' =>  ['--Please Select Country--'],
                ]
            );


         /*
            * Add Ajax to the Country select box html output
            */
      $country->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>"
        );
$form->setValues($model->getData());
        $this->setForm($form);

        return parent::_prepareForm();
    }

and create admin side action file to get region that is app\code[Vendor][ModuleName]\Controller\Adminhtml\Lists\Regionlist.php

<?php
/**
 *
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */

// @codingStandardsIgnoreFile

namespace [Vendor]\[ModuleName]\Controller\Adminhtml\Lists;

/**
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 */
class Regionlist extends \Magento\Framework\App\Action\Action
{
            /**
         * @var \Magento\Framework\View\Result\PageFactory
         */
        protected $resultPageFactory;
    /**
     * @var \Magento\Directory\Model\CountryFactory
     */
    protected $_countryFactory;

        /**
         * @param \Magento\Framework\App\Action\Context $context
         * @param \Magento\Framework\View\Result\PageFactory resultPageFactory
         */
        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);
        }
    /**
     * Default customer account page
     *
     * @return void
     */
    public function execute()
    {


        $countrycode = $this->getRequest()->getParam('country');
        $state = "<option value=''>--Please Select--</option>";
        if ($countrycode != '') {
            $statearray =$this->_countryFactory->create()->setId(
                    $countrycode
                )->getLoadedRegionCollection()->toOptionArray();
            foreach ($statearray as $_state) {
                if($_state['value']){
                    $state .= "<option >" . $_state['label'] . "</option>";
            }
           }
        }
       $result['htmlconent']=$state;
         $this->getResponse()->representJson(
            $this->_objectManager->get('Magento\Framework\Json\Helper\Data')->jsonEncode($result)
        );
    } 

  }

once you change country region will load same way you can do for city also

If any one know better then this solution as like in we use in edit.phtml please share us

1
  • Okay will try your answer.
    – Amy
    Apr 10 '20 at 6:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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