2

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 ? – Yogesh Nov 7 '17 at 11:07
4

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 Jun 19 '19 at 13:03
  • This only returns the countries for the default store. Is there a way to return the countries from all stores? – Jonas de Herdt Nov 6 '20 at 8:36
1

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, privacy policy and cookie policy

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