1

I need to get the full name (es: "English (United State)") from my store views' locale code in Magento2.

I use

$scopeConfig->getValue('general/locale/value', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $_store->getStoreId());

inside a foreach to get all store views' locale code.

I need to get the fullname(es: "English (United State)") and NOT the LocaleCode (en_US)

0

Try this code:

/**
 * @var \Magento\Framework\Locale\Deployed\Options
 */
protected $localeOptions;

/**
 * @var string
 */
protected $localeName;

/**
 * @var \Magento\Framework\Locale\Resolver
 */
protected $localeResolver;

/**
 * Location constructor.
 *
 * @param \Magento\Framework\Locale\Resolver $localeResolver
 * @param \Magento\Framework\Locale\Deployed\Options $localeOptions
 * @throws \Exception
 */
public function __construct(
    \Magento\Framework\Locale\Resolver $localeResolver,
    \Magento\Framework\Locale\Deployed\Options $localeOptions
) {
    $this->localeResolver = $localeResolver;
    $this->localeOptions = $localeOptions;
    $this->localeName = $this->findLocaleName();
}

/**
 * Find locale name by its code
 * 
 * @return mixed
 * @throws \Exception
 */
public function findLocaleName()
{
    $locale = $this->localeResolver->getLocale();
    $availableLocales = $this->localeOptions->getTranslatedOptionLocales();
    foreach ($availableLocales as $candidate) {
        if (!empty($candidate['value']) && $candidate['value'] == $locale) {
            if (empty($candidate['label'])) {
                throw new \Exception(__('Empty locale label'));
            }
            return $candidate['label'];
        }
    }

    throw new \Exception(__('Locale %1 was not found', $locale));
}

It will return the locale name, like Afrikaans (Suid-Afrika) / Afrikaans (South Africa) for the af_ZA. Keep in mind, that locale name returns for the currently active locale for current store. If you wish to make different logic - fell free to update this code by yourself, or drop few lines with a clarification for me here and I'll try to help you in changing this code to suit your needs.

  • TY. it works perfectly – Gohan89 Mar 7 '18 at 15:28
0

Please try this you will get current localae code of the site,

<?php
public function __construct(
    ...
    \Magento\Store\Model\StoreManagerInterface $store,
    ...
) {
    ...
    $this->_store = $store;
    ...
}

public function getStoreLocale()
{
    return $this->_store->getStore()->getName(); 

}
?>
  • I need the full name, not the Locale code – Gohan89 Mar 2 '18 at 11:08
  • @Gohan89 please see my updated answer – Jeeva Chezhiyan Mar 2 '18 at 11:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.