We sacrifice by not doing any other technology, so that you get the best of Magento.

We sacrifice by not doing any other technology, so that you get the best of Magento.

If you want to add country and region inside the drop-down in custom module admin form, you landed to right page.

 

Follow below instruction step-by-step to execute it.

Step 1 : Add column in table field.

Create new file : Setup/Installschema.php

<?php

->addColumn(
'country',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'2M',
['nullable' => false],
'country' 
)->addColumn(
'store_ids',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'255',
['nullable' => false,
'default' => $defaultstoreid,
],
'store_ids' 
)->addColumn(
'statename',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'2M',
['nullable' => false],
'statename'
)

?>

Step 2 : Add country and state drop-down with text

Create new file : Block/Adminhtml/Grid/Edit/Form.php

<?php
$optionsc=$this->_countryFactory->toOptionArray();
$country = $fieldset->addField(
'country',
'select',
[
'name' => 'country',
'label' => __('Country'),
'title' => __('country'),
'values' => $optionsc,
]
);

$statename = $fieldset->addField(
'state',
'select',
[
'name' => 'state',
'label' => __('State'),
'id' => 'state',
'title' => __('state'),
'class' => 'required-entry',
'required' => false,
'values' => ['--Please Select State--'],
]
);
$fieldset->addField(
'statename',
'text',
[
'name' => 'statename',
'label' => __('State'),
'id' => 'statename',
'title' => __('state'),
'class' => 'statename',
'required' => false,
]
);

/*
* 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) {
jQuery('.field-statename').hide();

jQuery('#addressbook_country').change(function(){
var conceptName = jQuery('#addressbook_country').find(':selected').val();
jQuery.ajax({
url : '". $this->getUrl('grid/lists/regionlist') . "?country=' + conceptName,
data: conceptName,
type: 'GET',
dataType: 'json',
showLoader:true,
success: function(data){
// console.log(data.htmlconent);
if(data.htmlconent==''){
jQuery('.field-statename').show();
jQuery('.field-state').hide();
}else{
jQuery('#addressbook_state').empty().append(data.htmlconent);
jQuery('.field-state').show();
jQuery('.field-statename').hide();

}

}
}); 
});

}

);
</script>"
);

$statename->setAfterElementHtml(" 
<script type=\"text/javascript\">
require([
'jquery',
'mage/template',
'jquery/ui',
'mage/translate'
],
function($, mageTemplate) {
jQuery('.field-statename').hide();
jQuery(window).load(function(){
setTimeout(function(){
var statename ='".$model->getState()."';
jQuery('#addressbook_state option').each(function (a, b) {
if (jQuery(this).text().toLowerCase() == statename.toLowerCase() ){
jQuery(this).attr('selected','selected');
jQuery(this).trigger('change');

}
});
}, 1000);
});



var conceptName = jQuery('#addressbook_country').find(':selected').val();
if(conceptName != ''){
jQuery('#addressbook_country').trigger('change');
}
}

);
</script>"
);

?>

Step 3 : Getting region list from controller.

Create new file : Controller/Adminhtml/Lists/Regionlist.php

/**
* @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');

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

}

?>

Step 4 : Save your data.

Create new file : Controller/Adminhtml/Grid/Save.php

<?php

class Save extends \Magento\Backend\App\Action
{
/**
* @var \Namespace\Modulename\Model\GridFactory
*/
var $gridFactory;

/**
* @param \Magento\Backend\App\Action\Context $context
* @param \Namespace\Modulename\Model\GridFactory $gridFactory
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Namespace\Modulename\Model\GridFactory $gridFactory,
\Magento\Directory\Model\CountryFactory $countryFactory
) {
parent::__construct($context);
$this->gridFactory = $gridFactory;
$this->_countryFactory = $countryFactory;
}

/**
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function execute()
{
$data = $this->getRequest()->getPostValue();
if (!$data) {
$this->_redirect('grid/grid/addrow');
return;
}
try {

$countrycode = $data['country'];
$statearray =$this->_countryFactory->create()->setId($countrycode)->getLoadedRegionCollection()->toOptionArray();
$rowData = $this->gridFactory->create(); 
if($data['state'] == '0' || count($statearray) == 0){

$data['state'] = $data['statename'];
}
$data['store_ids'] = implode(',', $data['store_ids']); 
$rowData->setData($data);
if (isset($data['id'])) {
$rowData->setEntityId($data['id']);
}
$rowData->save();
$this->messageManager->addSuccess(__('AddressBook has been successfully saved.'));
} catch (\Exception $e) {
$this->messageManager->addError(__($e->getMessage()));
}
$this->_redirect('grid/grid/index');
}

/**
* @return bool
*/
protected function _isAllowed()
{
return $this->_authorization->isAllowed('Namespace_Modulename::save');
}
}
?>

Well, that’s it. Try to adopt this solution and let us know how it worked for you.

Fill the below form if you need any Magento relate help/advise/consulting.

With Only Agency that provides a 24/7 emergency support.

    Recent Articles
    Get a Free Quote