如何解决如何获得 Magento 2 Country Collection
希望你一切顺利。
我想以以下格式获取所有国家/地区。
$countries = [
"AU" => "Australia","IN" => "India","US" => "United States","UK" => "United Kingdom",.......
]
我尝试过但没有用,我总是将 CountryId 设为 2 位数字名称,例如
$countries = [
0 => "AU",1 => "IN",2 => "US",3 => "UK",.......
]
我使用了以下代码
Magento\Directory\Model\ResourceModel\Country\Collection::loadByStore()
我如何在 Magento 2 中实现这一点?
提前致谢。
解决方法
我认为您需要遍历国家/地区集合并创建一个以国家/地区代码为键、以国家/地区名称为值的新数组。你可以试试这样的吗?
public function __construct(
\Magento\Backend\Block\Template\Context $context,\Magento\Directory\Model\ResourceModel\Country\CollectionFactory $countryCollectionFactory,\Magento\Directory\Model\CountryFactory $countryFactory,array $data = []
) {
$this->countryCollectionFactory = $countryCollectionFactory;
$this->countryFactory = $countryFactory;
parent::__construct($context,$data);
}
public function getCountryName($countryCode){
$country = $this->countryFactory->create()->loadByCode($countryCode);
return $country->getName();
}
public function getCountryCollection()
{
$collection = $this->countryCollectionFactory->create()->loadByStore();
return $collection;
}
public function getCountries()
{
$countryCollection = $this->getCountryCollection();
$countries = [];
foreach ($countryCollection->getData() as $country) {
$countries[$country['country_id']] = $this->getCountryName($country['country_id']);
}
return $countries;
}
然后在您的模板中,您可以使用 $block->getCountries() 获取国家/地区。
结果:
array(249) { ["AD"]=> string(7) "Andorra" ["AE"]=> string(28) "Verenigde Arabische Emiraten" ["AF"]=> string(11) "Afghanistan" ["AG"]=> string(18) "Antigua en Barbuda" ["AI"]=> string(8) "Anguilla" ["AL"]=> string(8) "Albanië" ["AM"]=> string(8) "Armenië" ["AN"]=> NULL ["AO"]=> string(6) "Angola" ["AQ"]=> string(10) "Antarctica" ["AR"]=> string(11) "Argentinië" ["AS"]=> string(16) "Amerikaans-Samoa" ["AT"]=> string(10) "Oostenrijk" ["AU"]=> string(10) "Australië" ["AW"]=> string(5) "Aruba" ["AX"]=> string(6) "Åland" ...
,
使用我的简单代码:(可以ez注入类)
public function getCountries()
{
/** @var \Magento\Directory\Model\ResourceModel\Country\CollectionFactory $countryCollectionFactory */
$countryCollectionFactory = $this->_objectManager->get(\Magento\Directory\Model\ResourceModel\Country\CollectionFactory::class);
/** @var \Magento\Directory\Model\ResourceModel\Country\Collection $countryCollection */
$countryCollection = $countryCollectionFactory->create();
$countryCollection = $countryCollection->toOptionArray();
return array_column($countryCollection,'label','value');
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。