3

I need to get the the Selected Allowed Countries in a phtml file..

How can i get that ?

1
  • you have created custom or for default ? Commented Nov 7, 2017 at 11:07

2 Answers 2

6

You can fetch the Allowed Countries List using the below Code:

public function __construct(
    /* Add below dependencies */
    \Magento\Directory\Model\AllowedCountries $allowedCountryModel
) {
    $this->allowedCountryModel = $allowedCountryModel;
}

//Call the below function to fetch countires        
$this->allowedCountryModel->getAllowedCountries()   
2
  • 1
    this returns only shortcode of all countries. How can i get full names too?
    – Khushbu
    Commented Jun 19, 2019 at 13:03
  • This only returns the countries for the default store. Is there a way to return the countries from all stores? Commented Nov 6, 2020 at 8:36
2

You can utilise the getCountryCollection method in Magento's Directory Helper as it filters the returned collection to contain allowed countries only.

Example:

use Magento\Directory\Helper\Data as DirectoryHelper;
use Magento\Directory\Model\Country;

/**
 * Allowed Countries
 */
class AllowedCountriesProvider {

   /**
    * @var DirectoryHelper
    */
    protected $directoryHelper;

   /**
    * @param DirectoryHelper $directoryHelper
    */
    public function __construct(
        DirectoryHelper $directoryHelper
    )
    {
        $this->directoryHelper = $directoryHelper;
    }

   /**
    * Allowed Countries Getter.
    */
    public function getAllowedCountries()
    {
        $countries = [];

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

        return $countries;
    }
}

Reference:

https://github.com/magento/magento2/blob/2.4-develop/app/code/Magento/Directory/Helper/Data.php#L174

https://github.com/magento/magento2/blob/2.4-develop/app/code/Magento/Directory/Model/ResourceModel/Country/Collection.php#L160

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.