Back to Top

How to Add the Customer Default Billing Address to the Quote Programmatically?

Updated 6 March 2023

In this blog, we will see how to add the default customer billing address to the quote programmatically in Magento 2.

For setting the data in the quote we need the Quote object.
By using the customer id we can get the customer’s default billing address.

And Address class object in the quote contains the setter and getter methods to set and get the address data. Using this we are going to put the address in quotes.

Let me show you how…..

    public function __construct(
        \Magento\Quote\Api\CartRepositoryInterface $quoteRepository,
        \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
        \Magento\Customer\Model\AddressFactory $addressFactory,
        \Magento\Customer\Model\SessionFactory $customerSessionFactory,
    ) {
        $this->quoteRepository = $quoteRepository;
        $this->customerRepository = $customerRepository;
        $this->addressFactory  = $addressFactory;
        $this->_customerSessionFactory = $customerSessionFactory;
    }

    public function setBillingAddressToQuote($cartId) {
        $quote = $this->quoteRepository->getActive($cartId);
        
        $customerId = $this->_customerSessionFactory->create()->getCustomerId();

        //get customer default billing address using customerId.
        $customer = $this->customerRepository->getById($customerId);
        $billingAddressId = $customer->getDefaultBilling();
        $billingAddress = $this->addressFactory->create()->load($billingAddressId);
        $address = $billingAddress->getData();

        //now setting the address as the quote billing address
        $quote->getBillingAddress()->setFirstname($address['firstname']);
        $quote->getBillingAddress()->setLastname($address['lastname']);
        $quote->getBillingAddress()->setStreet($address['street']);
        $quote->getBillingAddress()->setCity($address['city']);
        $quote->getBillingAddress()->setTelephone($address['telephone']);
        $quote->getBillingAddress()->setPostcode($address['postcode']);
        $quote->getBillingAddress()->setCountryId($address['country_id']);
    }

Default magento class module-quote/Model/Quote/Address.php. Here, in this class, we can see all the methods to set data in the quote.

Searching for an experienced
Magento Company ?
Find out More

Similarly, using this technique we can not only set the customer’s default billing address but also can use the data from any source we are getting.

Thank you for checking this blog. Please let me know if you find any issues.

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home