Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Allregion.php
Go to the documentation of this file.
1 <?php
7 
15 {
19  protected $_countries;
20 
24  protected $_options;
25 
30 
35 
40  public function __construct(
41  \Magento\Directory\Model\ResourceModel\Country\CollectionFactory $countryCollectionFactory,
42  \Magento\Directory\Model\ResourceModel\Region\CollectionFactory $regionCollectionFactory
43  ) {
44  $this->_countryCollectionFactory = $countryCollectionFactory;
45  $this->_regionCollectionFactory = $regionCollectionFactory;
46  }
47 
52  public function toOptionArray($isMultiselect = false)
53  {
54  if (!$this->_options) {
55  $countriesArray = $this->_countryCollectionFactory->create()->load()->toOptionArray(false);
56  $this->_countries = [];
57  foreach ($countriesArray as $a) {
58  $this->_countries[$a['value']] = $a['label'];
59  }
60 
61  $countryRegions = [];
62  $regionsCollection = $this->_regionCollectionFactory->create()->load();
63  foreach ($regionsCollection as $region) {
64  $countryRegions[$region->getCountryId()][$region->getId()] = $region->getDefaultName();
65  }
66  uksort($countryRegions, [$this, 'sortRegionCountries']);
67 
68  $this->_options = [];
69  foreach ($countryRegions as $countryId => $regions) {
70  $regionOptions = [];
71  foreach ($regions as $regionId => $regionName) {
72  $regionOptions[] = ['label' => $regionName, 'value' => $regionId];
73  }
74  $this->_options[] = ['label' => $this->_countries[$countryId], 'value' => $regionOptions];
75  }
76  }
78  if (!$isMultiselect) {
79  array_unshift($options, ['value' => '', 'label' => '']);
80  }
81 
82  return $options;
83  }
84 
90  public function sortRegionCountries($a, $b)
91  {
92  return strcmp($this->_countries[$a], $this->_countries[$b]);
93  }
94 }
__construct(\Magento\Directory\Model\ResourceModel\Country\CollectionFactory $countryCollectionFactory, \Magento\Directory\Model\ResourceModel\Region\CollectionFactory $regionCollectionFactory)
Definition: Allregion.php:40