如何在Magento2中添加国家和国家下拉列表
-
13-12-2019 - |
题
我需要在admin表单中添加国家和州下降,如何执行它
解决方案
在_prepareform()添加国家和区域中的admin表单块中
是
在__construct()添加国家/地区配置源
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,
\Sugarcode\Test\Model\Status $status,
array $data = []
) {
$this->_systemStore = $systemStore;
$this->_wysiwygConfig = $wysiwygConfig;
$this->_status = $status;
$this->_countryFactory = $countryFactory;
parent::__construct($context, $registry, $formFactory, $data);
}
.
和_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();
}
.
并创建管理员侧操作文件以获取区域 那是 app \ code \ sugarcode \ test \ controller \ controller \ adminhtml \ lists \ regionList.php
<?php
/**
*
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
// @codingStandardsIgnoreFile
namespace Sugarcode\Test\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)
);
}
}
.
一旦您更改国家区域将加载与城市的相同方式
如果任何一个人知道更好,那么这个解决方案就像我们在Edit.phtml中使用,请分享我们
其他提示
在块构造函数中,您需要使用区域和国家的集合启用两个类。另外,不要忘记在那里添加相应的字段。
接下来,请使用lib / web / varien / form.js应用标准RegionUpdater。它可以在任何方便的方式中添加 - 在我们的示例中,我们正在使用一个子块,其中包含它的模板,在那里调用它(只请注意一些必需的参数:国家元素,区域(文本),区域(选择)和包含国家和地区数据的对象(来自辅助目录)。
如果需要修改国家和地区列表,不仅可以在表单中,还可以在RegionUpdater中的数据对象中。表单块类中的更改,将新类添加到di,__construct方法并对_prepareform方法进行更改。
<?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]
);
$fieldset->addField(
'region',
'text',
['name' => 'region', 'label' => __('Region')]
);
$fieldset->addField(
'city',
'text',
['name' => 'city', 'label' => __('City')]
);
$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>
.
这是它的工作原理:
1)默认
2)选择USD后,隐藏区域的文本字段(第5个参数regionUpdater构造函数 - 此方法将应用于任何非活动字段,也可以隐藏或禁用)
3)对于阿尔巴尼亚,默认情况下没有地区。因此,我们可以看到与隐藏区域的文本字段:
4)对于瑞士,我们可以再次看到区域:
而且它不言而喻,您应该使您的客户端使用方便,就像使用隐藏方法一样,未隐藏归档标签。
但整体上,Regionupdater适用于非UI形式的Magento。
p.s。另请注意,没有办法为城市添加更新程序,默认情况下,Magento不支持城市列表。
您可以尝试使用/ replicationg配置模块的方式。
添加js.phtml块,该块也用于运输原点配置,到您的布局XML。
<referenceContainer name="js">
<block class="Magento\Backend\Block\Template" template="Magento_Config::system/config/js.phtml"/>
</referenceContainer>
.
将字段ID命名为“country_id”和“Region_ID”,并将“Countryers”CSS类添加到Country_ID字段。
$fieldset->addField(
'country_id',
'select',
[
'name' => 'country_id',
'label' => __('Country'),
'title' => __('Country'),
'values' => array_merge(['' => ''], $this->_countryOptions->toOptionArray()),
'class' => 'countries',
]
);
$fieldset->addField(
'region_id',
'text',
[
'name' => 'region_id',
'label' => __('Region/State'),
'title' => __('Region/State'),
]
);
.