3

I'm trying to get Region from shipping address. Here's the code :

$customer = $this->customerRepository->get('xxx@xxx.com');
$shippingAddressId = $customer->getDefaultShipping();
$shippingAddress = $this->addressRepository->getById($shippingAddressId);
$shippingAddress->getRegion();

But I'm not getting string of region name, instead I got Object from Magento\Customer\Model\Data\Region

The country is not United States, so Region is simply string ( input text form ) instead of select, so no Region Id / Region Code when I created the customer from admin.

So, how correct way to get Region from shipping when there are no region id / region code?

1

I tried to look inside Magento\Customer\Model\Data\Region, and inside it there is a code :

/**
     * Get region
     *
     * @return string
     */
    public function getRegion()
    {
        return $this->_get(self::REGION);
    }

So I use $shippingAddress->getRegion()->getRegion(); to get correct region name.

Still, the code look kinda weird, and I hope there are more answer to just use $shippingAddress->getRegion() and got the string of region name i need.

0

Try the below code to get Region from default shipping addresss

protected $customerSession;

public function __construct(
    ...
    \Magento\Customer\Model\Session $customerSession
)
{
    ...
    $this->customerSession = $customerSession;
    parent::__construct($context);
}

public function getRegion() {
    $customer = $this->customerSession->getCustomer();
    if ($customer) {
        $shippingAddress = $customer->getDefaultShippingAddress();
        if ($shippingAddress) {
            return $shippingAddress->getRegion();
        }
    }
    return null;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.