How to get country of origin of the store from configuration
-
11-05-2021 - |
La solution
Here are the code to get country, region and zip code
<?php
use Magento\Directory\Model\CountryFactory;
use Magento\Directory\Model\RegionFactory;
use Magento\Framework\App\Config\ScopeConfigInterface;
class MyClass
{
/**
* @var ScopeConfigInterface
*/
protected $scopeConfig;
/**
* @var CountryFactory
*/
protected $countryFactory;
/**
* @var RegionFactory
*/
protected $regionFactory;
/**
* MyClass constructor.
* @param ScopeConfigInterface $scopeConfig
* @param CountryFactory $countryFactory
* @param RegionFactory $regionFactory
*/
public function __construct(
ScopeConfigInterface $scopeConfig,
CountryFactory $countryFactory,
RegionFactory $regionFactory
) {
$this->scopeConfig = $scopeConfig;
$this->countryFactory = $countryFactory;
$this->regionFactory = $regionFactory;
}
/**
* Get shipping country name
* @return string
*/
public function getShippingCountry()
{
$countryCode = $this->scopeConfig->getValue(
'shipping/origin/country_id',
\Magento\Store\Model\ScopeInterface::SCOPE_STORE
);
$country = $this->countryFactory->create()->loadByCode($countryCode);
return $country->getName();
}
/**
* Get shipping region name
* @return string
*/
public function getShippingRegion()
{
$regionId = $this->scopeConfig->getValue(
'shipping/origin/region_id',
\Magento\Store\Model\ScopeInterface::SCOPE_STORE
);
$region = $this->regionFactory->create()->load($regionId);
return $region->getName();
}
/**
* Get shipping postcode
* @return string
*/
public function getShippingPostcode()
{
return $this->scopeConfig->getValue(
'shipping/origin/postcode',
\Magento\Store\Model\ScopeInterface::SCOPE_STORE
);
}
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à magento.stackexchange