I need to get the the Selected Allowed Countries in a phtml file..
How can i get that ?
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()
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