How to get Region text from address id (Magento 2)
-
21-02-2021 - |
Question
I am not able to get region text from address id,
<?php $_pAddsses = $block->getDefaultBilling() ?>
<?php echo $block->getAddressById($_pAddsses)->getRegionId() ?>
// output 5
<?php echo $block->getAddressById($_pAddsses)->getRegion() ?>
//output ""(empty)
And for my question, I don't have any region code, as many countries don't have region dropdown, like - India country dropdown doesn't have region dropdown, so in the database, the region id is 0 and region is whatever we filled in the text box for the region.
I checked the database it does contain region text.
I need region text to populate the region text box for which region dropdown
is not available for countries.
I am not able to figure out what am I doing wrong.
Solution
You can try following code to get the region from the address id.
$address = $this->addressRepository->getById($addressId);
$address->getRegion()->getRegion();
where $this->addressRepository
is the object of Magento\Customer\Api\AddressRepositoryInterface
$address->getRegion()
will give return you the object of Magento\Customer\Api\Data\RegionInterface
and then calling getRegion()
on it will give you string.
OTHER TIPS
In Block File :-
protected $AddressRepoInterface;
public function __construct(
\Magento\Customer\Api\AddressRepositoryInterface $AddressRepoInterface
){
$this->AddressRepoInterface = $AddressRepoInterface;
}
public function getRegionName() {
return $this->AddressRepoInterface->getById($addressId)->getRegion();
}
In phtml File :-
$block->getRegionName();