0

I try to -> use Magento\Directory\Helper\Data as DirectoryHelper;

protected $directoryHelper;

DirectoryHelper $directoryHelper,

$this->directoryHelper = $directoryHelper;

public function getAllowedCountries()
    {
        $countries = [];

        /* @var Country $country */
        foreach ($this->directoryHelper->getCountryCollection() as $country) {
            $countries[] = [
                'value' => $country->getId(),
                'label' => $country->getName()
            ];
        }

        return $countries;
    }

1 Answer 1

0

In Magento 2, you can use the \Magento\Directory\Model\Country model and the \Magento\Store\Model\StoreManager class to get the list of allowed countries by store code. Here is an example of how you can do this:

  1. Inject the \Magento\Directory\Model\Country model and the \Magento\Store\Model\StoreManager class into your class constructor.
use Magento\Directory\Model\Country;
use Magento\Store\Model\StoreManager;

class YourClass {
    protected $country;
    protected $storeManager;
    public function __construct
    (
        Country $country, StoreManager $storeManager
    ) {
        $this->country = $country;
        $this->storeManager = $storeManager;
    }
}
  1. Get the store code by using the getCode() method of the StoreManager class.

$storeCode = $this->storeManager->getStore()->getCode();

  1. Use the getAllowedCountries method of the Country model and pass the store code as a parameter.

$allowedCountries = $this->country->getAllowedCountries($storeCode);

This will return an array of allowed countries for the store with the specified store code. Please note that the allowed countries can be defined in the store configuration settings.

You can also filter the countries by using the getList method of the Country model and passing the allowed countries array as a parameter.

> $countries = $this->country->getList(); $allowedCountries =
> array_intersect_key($countries, array_flip($allowedCountries));
1
  • Magento\Directory\Model\Country does't have a getAllowedCountries method. Thee is however a Magento\Directory\Model\AllowedCountries::getAllowedCountries method.... Commented Jun 14 at 12:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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