I'm trying to add a custom field in between the shipping address and shipping method sections. And I want values of this field to be stored in both quote
and sales_order
tables ultimately. This is something similar to adding an "order comment" field but this field should appear right after the shipping address section and before the shipping method section.
I went through Magento dev guides on how to add a custom field and a custom form to the checkout and implemented a solution to a certain extent.
What I have done so far:
- Updated the
checkout_index_index.xml
layout, added a newuiComponent
(a container) under the item "shippingAddress". - Added the element (field) I require inside the container.
- Override the
/js/view/shipping.js
andshipping.phtml
in my custom module. - Invoked the above made container inside
shipping.phtml
in between checkout shipping address and shipping method (something similar to adding a new static form)
Now the field I want is being rendered on the onepage checkout exactly where I want. But I have met with below problems.
-
How to access the value of the custom field I have added above? I'm trying to save the value to a shippingAddress extension attribute. I added a mixin to
setShippingInformationAction
inside that try to do the belowshippingAddress['extension_attributes']['custom_field'] = shippingAddress.customAttributes['custom_field'];
But above code actually fails since the element is not in the shipping-address-fieldset
. I might be able to get the value through the window
element. But is there a way to access this through Magento?
- Is there a way to save the value of this element in local cache storage (
Magento_Checkout/js/checkout-data
) so the value will persist even after a page refresh?
Best Answer
Based on your question I'm under the assumption you already have your extension attributes set up. I have carried out a similar modification and hopefully my answer helps.
In your Custom module create a requirejs-config file to extend the default shipping processor/default
Add your extension attribute to the payload.
Save the Attribute to your Quote with a plugin (Not sure if you could use an observer here I have not checked).
di.xml
SaveAddressInformation.php
Save the Attribute to your order with an Observer events.xml
SaveCustomFieldToOrder.php