2

I'm trying to add an address column to my orders index but I'm having trouble correctly getting the actual address.

From my code below, when I dump on $orderShippingAddress I get the ID of a valid address. But when I dump on $address I get null.

Can anyone spot where I'm going wrong? For reference, I was working from here: https://craftcms.com/docs/commerce/3.x/addresses.html#get-current-customer-address-by-id

Event::on(
    Order::class,
    Order::EVENT_REGISTER_TABLE_ATTRIBUTES,
    function (RegisterElementTableAttributesEvent $event) {
        $event->tableAttributes['address'] = ['label' => 'Address'];
    }
);  

Event::on(
    Order::class,
    Order::EVENT_SET_TABLE_ATTRIBUTE_HTML,
    function (SetElementTableAttributeHtmlEvent $event) {
        $order = $event->sender;
        $orderShippingAddress = $order->shippingAddressId;
        $address = craft\commerce\Plugin::getInstance()->getCustomers()->getCustomer()->getAddressById($order->shippingAddressId);
        dump($shippingAddress);
        if ($event->attribute === 'address') {
             $event->html = $address;
        }
    }
);
3
  • 1
    What do you get if you just use the addresses service? $address = craft\commerce\Plugin::getInstance()->getAddresses()->getAddressById($order->shippingAddressId); Apr 7, 2022 at 9:06
  • Nice one! That does it!
    – supazu
    Apr 7, 2022 at 9:55
  • @MartinSpain if you add that as an answer I'll mark it accepted
    – supazu
    Apr 7, 2022 at 12:37

2 Answers 2

6

You can use the Addresses service to get the shipping address:

$address = craft\commerce\Plugin::getInstance()->getAddresses()->getAddressById($order->shippingAddressId);

This is the more direct method to get the address, and it's a bit shorter to type too!

1

You could also use $order->getShippingAddress() which is even shorter! :)

Your Answer

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

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