Magento 2 - Get Customer Address Id through Shipping Address at Checkout Session

梦想的初衷 提交于 2019-12-11 17:36:48

问题


I'm having trouble with getting customer address Id as it returns a null value.

This is what I have tried:

$checkout = $this->_sessionCheckout->getQuote();
if ($checkout) {
   $shippingAddress = $checkout->getShippingAddress();
   if ($shippingAddress) {
       $addressId = $shippingAddress->getCustomerAddressId();
       $this->_logger->log(100, print_r('address Id: ' . $addressId , true)); //Returns null 
       /** @var \Magento\Customer\Api\Data\AddressInterface $address */
       $address = $this->_addressRepository->getById($addressId);
       $address->setCity($city_name);
       $this->_addressRepository->save($address);
}

I just need to get customer address Id in order to update the city. I don't know why it returns a null value.

Thank you in advance.


Edited Details:

The below image shows the saved shipping addresses:

shipping-addresses

What I want to know is How to know the customer address id of each of those shipping addresses. So I can modify any details I want.


回答1:


When you place an order as a guest user, you have to add shipping address on checkout page at that time there will be not a customer reference object, so you get value of customer address Id to null.

When you place an order as a registered customer, you should have default shipping address, then only you can get the value of customer address Id.

This happen because customer_address_id is a reference to customer_address table and customer_address table reference to customer_entity table.




回答2:


You can get the order as follows Whereever your want to invoke this information add following in the Constructor if not already being used.

protected $checkoutSession;
public function __construct(
        \Magento\Checkout\Model\Session $checkoutSession,
        \Psr\Log\LoggerInterface $logger
    )
    {

        $this->checkoutSession = $checkoutSession;
        $this->logger = $logger;
    }


    $order = $session->getLastRealOrder();
    $orderdata = $order->getData();
    $shipping_address_id = $orderdata['shipping_address_ID'];

This address is the final shipping address selected during payment stage of the checkout process.



来源:https://stackoverflow.com/questions/54707427/magento-2-get-customer-address-id-through-shipping-address-at-checkout-session

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!