1
public function Address() { $customerId = "8"; $customer = $this->customerRepository->getById($customerId); $addresses = $customer->getAddresses(); $billingAddress = $customer->getDefaultBilling(); $shippingAddress = $customer->getDefaultShipping(); return $billingAddress; } 

In this code is only getting the id I want the address as a string.please help me.

4 Answers 4

0

As you are getting the Address Id, you need to load the Address using that Id. You can use the below code:

$address = $this->addressRepository->getById($billingAddressId); $renderer = $this->addressConfig->getFormatByCode('html')->getRenderer(); return $renderer->renderArray($this->addressMapper->toFlatArray($address)); 

In Contructor you need to define the below classes:

\Magento\Customer\Api\AddressRepositoryInterface $addressRepository, \Magento\Customer\Model\Address\Config $addressConfig, \Magento\Customer\Model\Address\Mapper $addressMapper 

You can change the argument passed in getFormatByCode function to text as well.

12
  • which address i will get from the above code?only billing? Commented Jul 28, 2017 at 11:29
  • No you can pass any address id Commented Jul 28, 2017 at 11:30
  • ok thanks...is there anyway to get all the addresses using the customer ID? Commented Jul 28, 2017 at 11:32
  • You can get all address collection like this $addresses = $customer->getAddresses(); Commented Jul 28, 2017 at 11:54
  • great ..If it worked for you, accept it as answer !! Commented Jul 28, 2017 at 11:55
0

You need to add dependency in the constructor method for class

\Magento\Customer\Model\AddressFactory $addressFactory 

And then to get address use below code

$billingAddress = $this->addressFactory->create()->load($billingAddressId); print_r($billingAddress->getData()); 

Same for shipping Address.

0

This will work Please check

$customerId = '9'; $customer = $this->_customerRepository->getById($customerId); $addresses = $customer->getAddresses(); 

Please note that getAddresses will return an array of

Magento\Customer\Api\Data\AddressInterface.

If you need the default billing address you can call:

$billingAddress = $customer->getDefaultBilling(); 
0

$customer->getDefaultBilling(); will return address id only, to get the default billing address object use: $customer->getDefaultBillingAddress();

And it works the same with shipping address as well.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.