2

enter image description hereMy Form.php File

<?php

namespace Meetanshi\Registration\Block\Adminhtml\Registration\Edit;
use Magento\Backend\Block\Widget\Form\Generic;
use Magento\Backend\Block\Template\Context;
use Magento\Framework\Registry;
use Magento\Framework\Data\FormFactory;
use Magento\Cms\Model\Wysiwyg\Config;
use Meetanshi\Registration\Model\Registration;
use Magento\Directory\Model\RegionFactory;
use Magento\Directory\Model\Config\Source\Country;

class Form extends Generic
{

    protected $_systemStore;
    protected $regionFactory;
    protected $countryFactory;

    public function __construct(
       Context $context,
        Registry $registry,
        FormFactory $formFactory,
        Config $wysiwygConfig,
        Registration $options,RegionFactory $regionFactory,Country $countryFactory,
        array $data = []
    )
    {
        $this->_options = $options;
        $this->_wysiwygConfig = $wysiwygConfig;

        $this->regionFactory = $regionFactory;
        $this->countryFactory = $countryFactory;
        parent::__construct($context, $registry, $formFactory, $data);
    }


    protected function _prepareForm()
    {
        //$dateFormat = $this->_localeDate->getDateFormat(\IntlDateFormatter::SHORT);
        $model = $this->_coreRegistry->registry('row_data');
        try {
            $form = $this->_formFactory->create(
                ['data' => [
                    'id' => 'edit_form',
                    'enctype' => 'multipart/form-data',
                    'action' => $this->getData('action'),
                    'method' => 'post'
                ]
                ]
            );
        }
        catch (\Exception $e){

            \Magento\Framework\App\ObjectManager::getInstance()->get('Psr\Log\LoggerInterface')->info($e->getMessage());
        }
        $form->setHtmlIdPrefix('wkgrid_');
        if ($model->getId()) {
            $fieldset = $form->addFieldset(
                'base_fieldset',
                ['legend' => __('Edit Row Data'), 'class' => 'fieldset-wide']
            );
            $fieldset->addField('id', 'hidden', ['name' => 'id']);
        } else {
            $fieldset = $form->addFieldset(
                'base_fieldset',
                ['legend' => __('Add Row Data'), 'class' => 'fieldset-wide']
            );
        }
        $fieldset->addField(
            'title',
            'select',
            [
                'name' => 'title',
                'label' => __('Title'),
                'id' => 'title',
                'title' => __('Title'),
                'class' => 'required-entry',
                'values' => ["mr"=>'Mr',"ms"=>'Ms',"mrs"=>'Mrs'],
                'required' => true,
            ]
        );
        $fieldset->addField(
            'firstname',
            'text',
            [
                'name' => 'firstname',
                'label' => __('First Name'),
                'id' => 'firstname',
                'title' => __('First Name'),
                'class' => 'required-entry validate-alpha',
                'required' => true,
            ]
        );
        $fieldset->addField(
            'lastname',
            'text',
            [
                'name' => 'lastname',
                'label' => __('Last Name'),
                'id' => 'lastname',
                'title' => __('Last Name'),
                'class' => 'required-entry',
                'required' => true,
            ]
        );
        $fieldset->addField(
            'email',
            'text',
            [
                'name' => 'email',
                'label' => __('Email'),
                'id' => 'email',
                'title' => __('Email'),
                'class' => 'required-entry',
                'required' => true,
            ]
        );
        $fieldset->addField('gender', 'radios', array(
            'label'     => __('Radios'),
            'name'      => 'gender',
            'values' => array(
                array('value'=>'male','label'=>'Male'),
                array('value'=>'female','label'=>'Female'),
            ),
            'disabled' => false,
            'readonly' => false

        ));
        $fieldset->addField(
            'dob',
            'date',
            [
                'name' => 'dob',
                'label' => __('DOB'),
                //'date_format' => $dateFormat,
                'date_format' => 'd-MM-y',
                'class' => 'validate-date validate-date-range date-range-custom_theme-from',
                'class' => 'required-entry',
                'style' => 'width:200px',
            ]
        );
        $fieldset->addField(
            'address',
            'text',
            [
                'name' => 'address',
                'label' => __('Address'),
                'id' => 'address',
                'title' => __('address'),
                'class' => 'required-entry',
                'required' => true,
            ]
        );
        $fieldset->addField(
            'address2',
            'text',
            [
                'name' => 'address2',
                'label' => __(''),
                'id' => 'address2',
                'title' => __('address2'),
                'class' => 'required-entry',
                'required' => true,
            ]
        );
        $fieldset->addField(
            'city',
            'text',
            [
                'name' => 'city',
                'label' => __('City'),
                'id' => 'city',
                'title' => __('city'),
                'class' => 'required-entry',
                'required' => true,
            ]
        );


        $fieldset->addField(
            'zip',
            'text',
            [
                'name' => 'zip',
                'label' => __('Zip'),
                'id' => 'zip',
                'title' => __('Zip'),
                'class' => 'required-entry',
                'required' => true,
            ]
        );
        $countries = $this->countryFactory->toOptionArray();
        $countryData = $fieldset->addField(
            'country',
            'select',
            [
                'name' => 'country',
                'data-form-part' => $this->getData('target_form'),
                'title' => __('Country'),
                'label' => __('Country'),
                'value' => $form['country'],
                'values' => $countries
            ]
        );

        $regionCollection = $this->regionFactory->create()->getCollection()->addCountryFilter($form['country']);
        $regions = $regionCollection->toOptionArray();

        $fieldset->addField(
            'state',
            'select',
            [
                'name' => 'state',
                'data-form-part' => $this->getData('target_form'),
                'title' => __('State'),
                'label' => __('State'),
                'values' =>  $regions,
                'value' => $form['state'],
            ]
        );
        $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('*/*/regionlist') . "country/' +  $('#country_id').val(),
                                type: 'get',
                                dataType: 'json',
                               showLoader:true,
                               success: function(data){
                                    $('#region_id').empty();
                                    $('#region_id').append(data.htmlconent);
                               }
                            });
                   })
                }

            );
            </script>"
        );

        $fieldset->addField(
            'phone_no',
            'text',
            [
                'name' => 'phone_no',
                'label' => __('Phone No'),
                'id' => 'phone_no',
                'title' => __('phone_no'),
                'class' => 'required-entry',
                'required' => true,
            ]
        );
        $form->setValues($model->getData());
        $form->setUseContainer(true);
        $this->setForm($form);

        return parent::_prepareForm();
    }
}

On Change ajex not working

1
  • Hi @arjun welcome to magento.stackexchange.com could you please share more details when posting the question so that other developers can understand easily and provide you a quick solution for your problem. Commented Jan 21, 2020 at 13:31

2 Answers 2

1

Here is your block file code

protected $_countryFactory;

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

protected function _prepareForm()
{
    // get region value from Modal
     if ($model->getId()) {
        $region_value = $model->getData('region');
    } else {
        $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>"
    );
    .....................................................
    .....................................................
    .....................................................
}

Now ajax return your option

Regionlist.php

<?php


namespace [vendor_name]\[Module_name]\Controller\Adminhtml\Storelocator;

/**
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 */
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='';
        }
        //echo " ".$countrycode." ".$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)
        );
    }

  }

I Hope this helps you

3
  • Have tried your solution, but the region's list doesn't change when I select a country. It doesn't offer any option. Don't see any errors in the logs, nor anything apart from this going wrong. Any suggestion on what I might have missed, linking some parts together or something?
    – Seb
    Commented Nov 10, 2020 at 4:08
  • please share your code . i will be help you to solve this.
    – Msquare
    Commented Nov 10, 2020 at 9:16
  • Hi Please help me to solve this magento.stackexchange.com/questions/346942/… Commented Sep 15, 2021 at 7:29
0

After making some efforts,i found mistake in id of country field and region(State) field, Thanks For Support!

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.