We have sorted fields on the post – https://sbdevblog.com/magento-2-apply-sort-order-on-shipping-address-at-checkout/
However, there is limitiation on the street fields. We can’t sort the street field by using the layout file. Then there must be some way to fix this issue. We often need to put sorting on street address as well.
Fortunately, There is a solution. Yes, We can sort street address by using plugin on on below class.
Magento\Checkout\Block\Checkout\LayoutProcessor
LayoutProcessor block is responsible to generate HTML of checkout forms. The process methods reads the nodes of layout of checkout in array forms. We simply can change output by using after method on the process function.
Magento 2: Apply sorting to street address on shipping form
We need to create di.xml file inside etc directory of our custom module. We will define plugin of above class in it.
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Checkout\Block\Checkout\LayoutProcessor">
<plugin name="validate_pobox_Checkout" type="SbDevBlog\Checkout\Plugin\Block\LayoutProcessor" sortOrder="100"/>
</type>
</config>
Then, We must create create a LayoutProcessor class defined as plugin. We must use key sortOrder to sort the street field.
<?php
/**
* @copyright Copyright (c) sbdevblog (http://www.sbdevblog.com)
*/
namespace SbDevBlog\Checkout\Plugin\Block;
class LayoutProcessor
{
/**
* Add POBOX Validation to street address on street address
*
* @param \Magento\Checkout\Block\Checkout\LayoutProcessor $subject
* @param array $jsLayout
* @return array
*/
public function afterProcess(
\Magento\Checkout\Block\Checkout\LayoutProcessor $subject,
array $jsLayout
)
{
$jsLayout['components']['checkout']['children']['steps']['children']['shipping-step']
['children']['shippingAddress']['children']['shipping-address-fieldset']
['children']['street']['sortOrder'] = 5;
return $jsLayout;
}
}
Keep in mind that we can also use plugin to sort all other fields as well. It is on our choice on based of requirements. If sorting is static than we must use layout. To allow admin to sort dynamically from backend, We must use plugin. Plugins are convenient to change the arguments or result.
In this post, we have sorted street address and put under the last name field.
I hope you liked our posts. Please subscribe to SbDevBlog. I will keep you posted technical stuff.
Thank you for reading the post: Magento 2: Apply sorting to street address on shipping form. Please use comment section for your valuable feedback.
Note: Please verify the code of this blog and the relevant git repository before using it in production.
🙂 HAPPY CODING 🙂