Add a custom form to Magento 2 checkout on the first step.
Add a custom form fields to the Magento 2 checkout. The form will appear in the first checkout step (shipping step) above shipping methods.
The form is available for logged in customers and guests. After an order is placed all data are set in sales_order
table.
Data are still in the form after page refreshed, till cart is active., (*1)
Form data will be set in a quota
table through independent API request:
- /V1/carts/mine/set-order-custom-fields
(for logged in customer)
- /V1/guest-carts/:cartId/set-order-custom-field
(for guest), (*2)
composer require sbodak/magento2-checkout-custom-form
php bin/magento module:enable Bodak_CheckoutCustomForm
php bin/magento setup:upgrade
Api/Data/CustomFieldsInterfaces.php
Setup/InstallData.php
Observer/AddCustomFieldsToOrder.php
which save data in quota and sales tableview/frontend/layout/checkout_index_index.xml
Model/Data/CustomFields.php
Model/CustomFieldsRepository.php
<item name="custom-checkout-form-fieldset" xsi:type="array"> <item name="component" xsi:type="string">uiComponent</item> <item name="displayArea" xsi:type="string">custom-checkout-form-fields</item> <item name="children" xsi:type="array"> [... place here new definition of your field] </item> </item>
Check official documentation: https://devdocs.magento.com/guides/v2.3/howdoi/checkout/checkout_form.html, (*3)
view/frontend/templates/order/view/custom_fields.phtml
(for customer account)
and view/adminhtml/templates/order/view/custom_fields.phtml (for admin panel)
.If you want to make field required, check this example:, (*4)
<item name="checkout_purchase_order_no" xsi:type="array"> <item name="component" xsi:type="string">Magento_Ui/js/form/element/abstract</item> <item name="config" xsi:type="array"> <item name="customScope" xsi:type="string">customCheckoutForm</item> <item name="template" xsi:type="string">ui/form/field</item> <item name="elementTmpl" xsi:type="string">ui/form/element/input</item> </item> <item name="validation" xsi:type="array"> <item name="required-entry" xsi:type="boolean">true</item> </item> <item name="provider" xsi:type="string">checkoutProvider</item> <item name="dataScope" xsi:type="string">customCheckoutForm.checkout_purchase_order_no</item> <item name="label" xsi:type="string">Purchase order no.</item> <item name="sortOrder" xsi:type="string">3</item> </item>
You can modify i18n/en_US.csv
translation to change field names., (*5)
, (*6)
, (*7)
, (*8)
, (*9)
To remove this module run php bin/magento module:uninstall Bodak_CheckoutCustomForm
.
It will remove all data and drop columns in sales_order
and quote
tables., (*10)
MIT License, (*11)