Quantcast
Channel: Webkul Blog
Viewing all articles
Browse latest Browse all 5489

How to add the customer default billing address to the quote programatically.

$
0
0

In this blog we will see how to add the default customer billing address to the quote programatically in magento 2.

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

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

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.

Similarly, using this technique we can not only can set the customer 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 issue.


Viewing all articles
Browse latest Browse all 5489

Trending Articles