To get country collection in toOptionArray, you need to add following code in your file:
First you need to inject a \Magento\Directory\Model\ResourceModel\Country\CollectionFactory in your class constructor:
protected $_countryFactory; public function __construct( \Magento\Directory\Model\ResourceModel\Country\CollectionFactory $countryFactory ) { $this->_countryFactory= $countryFactory; }
Then in your class you can do:
public function getAllOptions() { return $options = $this->getCountryCollection()->toOptionArray(); } public function getCountryCollection() { $collection = $this->_countryFactory->create()->loadByStore(); return $collection; }
Full Code:
protected $_countryFactory; public function __construct( \Magento\Directory\Model\ResourceModel\Country\CollectionFactory $countryFactory ) { $this->_countryFactory= $countryFactory; } public function getAllOptions() { return $options = $this->getCountryCollection()->toOptionArray(); } public function getCountryCollection() { $collection = $this->_countryFactory->create()->loadByStore(); return $collection; } public function getOptionValue($value) { foreach ($this->getAllOptions() as $option) { if ($option['value'] == $value) { return $option['label']; } } return false; }
Run php bin/magento setup:di:compile when you add any dependency injection.Because without php bin/magento setup:di:compile it throws error in code.