In this post I am going to explain how to get country name from country code in Magento 2.
1. Using Dependency Injection
Add below code snippet in Block class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | protected $_countryFactory; public function __construct( \Magento\Backend\Block\Template\Context $context, \Magento\Directory\Model\CountryFactory $countryFactory, array $data = [] ) { $this->_countryFactory = $countryFactory; parent::__construct($context, $data); } public function getCountryName($countryCode) { $country = $this->_countryFactory->create()->loadByCode($countryCode); return $country->getName(); } |
Add below code snippet in template file.
1 2 3 4 5 6 7 | //Your country code $countryCode = 'US'; // Get country name $countryName = $block->getCountryname($countryCode); echo $countryName; |
2. Using Object Manager
1 2 3 4 5 6 7 8 9 10 11 12 | $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $countryFactory = $objectManager->get('Magento\Directory\Model\CountryFactory')->create(); //Your country code $countryCode = 'US'; // Get country name $country = $countryFactory->loadByCode($countryCode); $countryName = $country->getName(); echo $countryName; |
Leave a Reply