In this post I am going to explain how to get country collection 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 $_countryCollectionFactory; public function __construct( \Magento\Backend\Block\Template\Context $context, \Magento\Directory\Model\ResourceModel\Country\CollectionFactory $countryCollectionFactory, array $data = [] ) { $this->_countryCollectionFactory = $countryCollectionFactory; parent::__construct($context, $data); } public function getCountryCollection() { $collection = $this->_countryCollectionFactory->create()->loadByStore(); return $collection; } |
Add below code snippet in template file.
1 2 3 4 5 6 | // Get country collection $countryCollection = $block->getCountryCollection(); echo "<pre>"; print_r($countryCollection->getData()); echo "</pre>"; |
2. Using Object Manager
1 2 3 4 5 6 7 8 9 10 | $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $countryCollectionFactory = $objectManager->get('Magento\Directory\Model\ResourceModel\Country\CollectionFactory'); // Get country collection $countryCollection = $countryCollectionFactory->create()->loadByStore(); echo "<pre>"; print_r($countryCollection->getData()); echo "</pre>"; |
Leave a Reply