Magento – Magento 2 checkout: how to make vat number required

checkoutmagento2vat

How can I make the vat tax required in the Magento-2 checkout? From the panel, I can set it as default only in the "create new account" form.

Best Answer

You can achieve via create plugin of class \Magento\Checkout\Block\Checkout\LayoutProcessor

On after method of function process(), add required field to vat id field

PLugin class

<?php
namespace {Vendorname}\{Module}\Plugin\Block\Magento\Checkout;


class LayoutProcessorPlugin
{
    public function afterProcess(
        \Magento\Checkout\Block\Checkout\LayoutProcessor $subject,
        array  $jsLayout
    )
    {

        if(isset(
            $jsLayout['components']['checkout']['children']['steps']['children']['shipping-step']
            ['children']['shippingAddress']['children']['shipping-address-fieldset']['children']['vat_id']
        )){
            $jsLayout['components']['checkout']['children']['steps']['children']['shipping-step']
            ['children']['shippingAddress']['children']['shipping-address-fieldset']['children']['vat_id']
            ['validation'] =[
                'required-entry' => true,
            ];
        }


        $configuration = $jsLayout['components']['checkout']['children']['steps']['children']['billing-step']['children']['payment']['children']['payments-list']['children'];
        foreach ($configuration as $paymentGroup => $groupConfig) {
            if (isset($groupConfig['component']) AND $groupConfig['component'] === 'Magento_Checkout/js/view/billing-address') {



                if(isset(
                    $jsLayout['components']['checkout']['children']['steps']['children']['billing-step']['children']
                    ['payment']['children']['payments-list']['children'][$paymentGroup]['children']['form-fields']
                    ['children']['vat_id']
                )){
                    $jsLayout['components']['checkout']['children']['steps']['children']['billing-step']['children']
                    ['payment']['children']['payments-list']['children'][$paymentGroup]['children']['form-fields']
                    ['children']['vat_id'] ['validation'] =[
                        'required-entry' => true,
                    ];
                }

            }
        }

        return $jsLayout;
    }

}

Define di.xml

<?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="add_required_field_to_vat_id" sortOrder="1"
                type="{Vendorname}\{Module}\Plugin\Block\Magento\Checkout\LayoutProcessorPlugin"/>
    </type>
</config>
Related Topic