Hello Magento Friends,
In Magento 2, the checkout process allows customers to choose multiple shipping addresses for an order, which is a feature known as “multi-shipping.” When using this feature, it’s important to manage and store additional custom data for each shipping address in a structured way. A common requirement is saving a custom field value on the quote_address model for each shipping address during a multi-shipping order process.
Steps to Save Custom Field Value to quote_address for Multi-Shipping Orders in Magento 2:
Step 1: First, we need to create a “events.xml“ file inside our extension at the following path
app\code\Vendor\Extension\etc\events.xml
Then add the code as follows
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd"> <event name="checkout_controller_multishipping_shipping_post"> <observer name="custom_multishipping_observer" instance="Vendor\Extension\Observer\SaveCustomFieldToQuoteAddress" /> </event> </config>
Step 2: After that, we need to create an “SaveCustomFieldToQuoteAddress.php” file inside our extension at the following path
app\code\Vendor\Extension\Observer\SaveCustomFieldToQuoteAddress.php
And add the code as given below
<?php namespace Vendor\Extension\Observer; use Magento\Framework\Event\Observer; use Magento\Framework\Event\ObserverInterface; use Magento\Quote\Api\CartRepositoryInterface; class SaveCustomFieldToQuoteAddress implements ObserverInterface { protected $quoteRepository; public function __construct( CartRepositoryInterface $quoteRepository ) { $this->quoteRepository = $quoteRepository; } public function execute(Observer $observer) { $request = $observer->getEvent()->getRequest(); $quote = $observer->getEvent()->getQuote(); // Assuming your custom field is 'custom_field' and is sent via POST $customFieldValue = $request->getPostValue('customfield'); // Check if value exists if (is_array($customFieldValue) && !empty($customFieldValue)) { // Iterate through each shipping address and assign the correct value foreach ($quote->getAllShippingAddresses() as $address) { $addressId = $address->getId(); // Check if a custom field value exists for this address ID if (isset($customFieldValue[$addressId])) { $address->setData('customfield', $customFieldValue[$addressId]); } } } // Save the quote to persist the data $this->quoteRepository->save($quote); } } ?>
Conclusion:
By following these steps, you can easily save and manage custom field values for multi-shipping orders in Magento 2. This is useful for scenarios where you need to capture additional data specific to each shipping address, such as special delivery instructions or custom notes. These steps ensure that you can capture and store custom information tied to shipping addresses for multi-shipping orders, and extend the functionality of Magento 2’s checkout process.
Happy Coding!