I have a very strange problem where the Magento\Framework\Locale\Resolver
does not return the correct locale for the current store view.
I have setup a store with two separate store views which have locales set to English and Swedish. I have also configured the stores to append the store code to the current URL.
class Example {
/** @var \Magento\Store\Model\StoreManagerInterface */
private $storeManager;
/** @var \Magento\Framework\Locale\Resolver */
private $resolver;
public function __construct(StoreManagerInterface $storeManager,
Resolver $resolver)
{
$this->storeManager = $storeManager;
$this->resolver = $resolver;
}
/**
* Get locale using resolver.
**/
public function getLocale()
{
return $this->resolver->getLocale();
}
/**
* Get locale using storemanager
**/
public function getLocaleCode()
{
return $this->storeManager->getStore()->getLocaleCode();
}
}
In the above code the getLocale()
and getLocaleCode()
always returns the locale of the default store view. I managed to solve this by using the ScopeConfigInterface
like this:
class Example {
/** @var \Magento\Framework\App\Config\ScopeConfigInterface */
private $scopeConfig;
public function __construct(ScopeConfigInterface $scopeConfig)
{
$this->scopeConfig = $scopeConfig;
}
public function getLocale()
{
return
$this->scopeConfig->getValue(
'general/locale/code',
ScopeInterface::SCOPE_STORE,
$this->storeManager->getStore()->getId()
);
}
}
Even though the above works I really would like to know why the resolver returns the incorrect locale for the current store? I am thinking that this might be some kind of weird caching issue, I have tried all the following without any success:
php bin/magento cache:clean
php bin/magento cache:flush
php bin/magento setup:di:compile
php bin/magento setup:upgrade
php bin/magento indexer:reindex
Best Answer
I simply use the following to get the store locale
and seems to work fine