Magento 2 Country Name not get translated when using countryFactory
题
My Magento site have about 10 different websites and one for each country. I have set the correct Locale
corresponding to each country (storeview).
I'm getting Country Name by using countryFactory
, the problem is, when switching Storeview, it doesn't get me the country name translated according to the Locale
i configured in the admin.
public function __construct(
\Magento\Directory\Model\CountryFactory $countryFactory
)
{
$this->countryFactory = $countryFactory;
}
public function getCountryName($code)
{
$_country = $this->countryFactory->create()->loadByCode($code);
if($_country)
{
return $_country->getName();
}
return false;
}
How do I get country name translated when switching the storeview?
解决方案
Use locale code as param in getName
<?php
public function __construct(
\Magento\Directory\Model\CountryFactory $countryFactory
) {
$this->countryFactory = $countryFactory;
}
public function getCountryName($code)
{
$_country = $this->countryFactory->create()->loadByCode($code);
if($_country) {
return $_country->getName('Your locale code');
}
return false;
}
Example:
<?php
public function __construct(
\Magento\Directory\Model\CountryFactory $countryFactory,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
)
{
$this->countryFactory = $countryFactory;
$this->_storeManager = $storeManager;
$this->scopeConfig = $scopeConfig;
}
public function getCountryName($code)
{
$_country = $this->countryFactory->create()->loadByCode($code);
if($_country) {
/* current store id */
$storeId = $this->_storeManager->getStore()->getId();
return $_country->getName($this->getStoreLocale($storeId));
}
return false;
}
private function getStoreLocale($storeId)
{
$locale = $this->scopeConfig->getValue('general/locale/code', \Magento\Store\Model\ScopeInterface:: SCOPE_STORE, $storeId);
return $locale;
}