Magento2 How to Get Country Code Collection

Fortunately magento2 introduces many ways to get data from collection. Here we are following from those of two approaches : 1. Get the country code collection by getting the instance of object manager class and get the method by passing class dependency to ‘get’ method of objectManager class instance: $o = \Magento\Framework\App\ObjectManager::getInstance(); $_countryCollectionFactory = $o->get('\Magento\Directory\Model\ResourceModel\Country\CollectionFactory'); $collection = $_countryCollectionFactory->create()->loadByStore(); var_dump($collection->getData()); 2. The Other approach is to create a class and inject CountryCollectionFactory dependency via constructor: Customer = $customer; parent::__construct($context, $data); $this->_countryCollectionFactory = $countryCollectionFactory; } public function getCountryCollection() { $collection = $this->_countryCollectionFactory->create()->loadByStore(); return $collection; } } ?> In above code we are creating a Block class and injecting our countryCollectionFactory as dependency and assigning to a property. The method getCountryCollection() gets the country collection by current store.

Leave a Reply

Your email address will not be published. Required fields are marked *