3

I know we can get formated customer addresses by calling,

$data = $customer->getPrimaryBillingAddress()->getFormated();

Is there a similar way to get shipping address and billing address of a order as a string?

This gives me a error

$order->getBillingAddress()->getData()->getFormated()
1
  • Oops silly mistake. getData was the problem
    – Dan
    Commented Jan 13, 2016 at 8:48

3 Answers 3

10
$billing = $order->getBillingAddress()->getFormated();
$shipping = $order->getShippingAddress()->getFormated();

getFormated supports an optional parameter that can be html or text.

4
  • What I want is formated order shipping address. Not customer shipping address
    – Dan
    Commented Jan 13, 2016 at 8:45
  • 1
    @Dan. Sorry, I should read more carefully. I edited the answer.
    – Marius
    Commented Jan 13, 2016 at 8:49
  • 1
    Hey guys, great question and answers, however I have a slight problem, what if address line 2 is supplied, how do I get that?
    – K.I
    Commented Mar 14, 2017 at 10:45
  • getFormated() is returning null inside Observer, using $order = $observer->getOrder(). Any idea why?
    – Braza
    Commented Aug 23, 2018 at 15:55
1

For some reason inside custom module observer on Magento 2.3 it didn't worked for me so I wrote below code for address summary. You can copy and save time ;)

$shipping_address = $order->getShippingAddress();
echo $shipping_address->getData("firstname").' '.$shipping_address->getData("lastname")."<br/>".
$shipping_address->getData("company")."<br/>".
$shipping_address->getData("street")."<br/>".
$shipping_address->getData("city")."<br/>".
$shipping_address->getData("region")."<br/>".
$shipping_address->getData("country_id")."<br/>".
$shipping_address->getData("postcode")."<br/>".
"T: ".$shipping_address->getData("telephone");
0

It looks like most of these answers are out of date. As of Magento 2.4.3 you'll want to do the following.

(Using Object Manager as the easiest way to refernce the right classes. Use dependency injection if you can.)

$objectManager = ObjectManager::getInstance();
$addressConfig = $objectManager->create(\Magento\Customer\Model\Address\Config::class);
$addressMapper = $objectManager->create(\Magento\Customer\Model\Address\Mapper::class);
$renderer    = $addressConfig->getFormatByCode('text')->getRenderer();

// Where $address instanceof \Magento\Customer\Api\Data\AddressInterface
$addressData = $addressMapper->toFlatArray($address);

// Where $address instanceof \Magento\Sales\Model\Order\Address
$customerAddress = $objectManager->create(\Magento\Customer\Api\Data\AddressInterface::class, ['data' => $address->getData()]);
$addressData = $addressMapper->toFlatArray($customerAddress);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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