1

In the Magento 2, how can I programmatically get customers full addresses as a string? I want to modify this code:

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

     return  $billingAddress;
}
4
  • What are you want to see as a desired result? Formatted address string? Commented Jul 28, 2017 at 7:18
  • i want as string.
    – srg
    Commented Jul 28, 2017 at 7:29
  • Please, update your question with your requirements so it can be more clear for other. Commented Jul 28, 2017 at 7:30
  • In magento 2 how can i programatically get customer full addresses in string type?
    – srg
    Commented Jul 28, 2017 at 7:46

1 Answer 1

1

You can format the customer's address as text like below

$renderer = $this->addressConfig->getFormatByCode('text')->getRenderer();
return $renderer->renderArray($this->addressMapper->toFlatArray($billingAddress));

In your constructor you need to define the below classes

\Magento\Customer\Model\Address\Config $addressConfig,
\Magento\Customer\Model\Address\Mapper $addressMapper

Find the different address formats in the below xml where are defined

vendor/magento/module-customer/etc/address_formats.xml
1
  • i have tried the above you have mentioned but getting Error response:""message": "Recoverable Error: Argument 1 passed to Magento\\Framework\\Api\\ExtensibleDataObjectConverter::toFlatArray() must implement interface Magento\\Framework\\Api\\ExtensibleDataInterface, array given, called in C:\\wamp64\\www\\firstmagento\\vendor\\magento\\module-customer\\Model\\Address\\Mapper.php on line 42 and defined in C:\\wamp64\\www\\firstmagento\\vendor\\magento\\framework\\Api\\ExtensibleDataObjectConverter.php on line 81""
    – srg
    Commented Jul 31, 2017 at 4:29

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