Ease VAT Number Display on Magento 2 Shipping Page

Table of Contents

  1. Introduction
  2. Understanding the Background
  3. Initial Setup
  4. Adding the Custom Checkbox and VAT Field
  5. Conclusion
  6. FAQ
Shopify - App image

Introduction

Imagine you are running an e-commerce store on the Magento 2 platform, focusing heavily on increasing user experience and compliance with taxation laws across different regions. The need to display a VAT number on the Shipping Page—only when a specific condition is met, becomes paramount. This conditional display of the VAT number can significantly enhance both user experience and administrative compliance. This blog post will guide you through the process of adding a VAT number field to the Magento 2 Shipping Page, ensuring it appears only when a particular checkbox is checked. Let's delve into the practical steps needed to achieve this functionality.

Understanding the Background

Magento 2 has revolutionized the e-commerce space by providing a scalable, feature-rich platform for online merchants. However, one frequent customization request is the conditional display of fields based on user input, such as showing a VAT number field only when a checkbox is ticked. The benefit of this customization is not merely aesthetic; it allows for better data capturing and compliance, enhancing both customer experience and backend management.

The primary goal here is to create a custom checkbox that, when checked, reveals the VAT number field and stores the data correctly in both the sales_order and quote_address tables. This ensures that the information captured is accurately stored and retrievable for both order processing and financial records.

Initial Setup

Before delving into the technical steps, ensure you have access to your Magento 2 backend and are familiar with the basics of XML, PHP, and Magento's structure. This guide assumes you're working with Magento versions 2.4.2 through 2.4.6, although the principles can be applied to other versions with minor adjustments.

  1. Backup Your Magento Store: Always begin by backing up your Magento store. This prevents any potential data loss during customization.

  2. Enable Developer Mode: Running Magento in developer mode allows you to see errors and warnings that might be suppressed in production mode.

    php bin/magento deploy:mode:set developer
    

Adding the Custom Checkbox and VAT Field

Step 1: Create a Custom Module

Customizations are better handled through Magento modules. Create a custom module named Custom_VatField.

File Structure

Create the following directory structure:

app/code/Custom/VatField/
├── etc
│   ├── module.xml
│   └── frontend
│       └── layout
│           └── checkout_index_index.xml
├── registration.php
├── Setup
│   └── InstallSchema.php
└── view
    └── frontend
        └── web
            └── js
                └── vat-field.js

module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Custom_VatField" setup_version="1.0.0"/>
</config>

registration.php

<?php
 \Magento\Framework\Component\ComponentRegistrar::register(
     \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Custom_VatField',
    __DIR__
 );

Step 2: Define Layout XML

checkout_index_index.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="checkout.root">
            <block class="Magento\Framework\View\Element\Template" name="vat-field" template="Custom_VatField::vat-field.phtml"/>
        </referenceBlock>
    </body>
</page>

Step 3: JavaScript for Conditional Display

vat-field.js

Create a JavaScript file to control the visibility of the VAT number field.

require(['jquery'], function($) {
    $(document).ready(function() {
        $('#custom-checkbox').change(function() {
            if ($(this).is(':checked')) {
                $('#vat-number').show();
            } else {
                $('#vat-number').hide();
            }
        });
    });
});

Step 4: Create the Template File

vat-field.phtml

This partial template will contain the checkbox and VAT number field.

<?php
$block->getLayout()->createBlock('Magento\Framework\View\Element\Template')->setTemplate('Custom_VatField::vat-field.phtml')->toHtml();
?>

<div>
    <input type="checkbox" id="custom-checkbox" name="custom_checkbox" /> Show VAT Number
    <input type="text" id="vat-number" name="vat_number" style="display:none;" placeholder="Enter VAT Number" />
</div>
<script type="text/javascript" src="<?php echo $block->getViewFileUrl('Custom_VatField::js/vat-field.js'); ?>"></script>

Step 5: Update the Database Schema

Create or modify the InstallSchema.php to add the necessary fields to the sales_order and quote_address tables.

InstallSchema.php

<?php
namespace Custom\VatField\Setup;

use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\DB\Ddl\Table;

class InstallSchema implements InstallSchemaInterface
{
    public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $installer = $setup;
        $installer->startSetup();

        if (!$installer->tableExists('quote_address')) {
            $table = $installer->getConnection()->newTable(
                $installer->getTable('quote_address')
            )

            ->addColumn(
                'vat_number',
                Table::TYPE_TEXT,
                255,
                ['nullable' => false],
                'VAT Number'
            );

            $installer->getConnection()->createTable($table);
        }

        if (!$installer->tableExists('sales_order')) {
            $table = $installer->getConnection()->newTable(
                $installer->getTable('sales_order')
            )

            ->addColumn(
                'vat_number',
                Table::TYPE_TEXT,
                255,
                ['nullable' => false],
                'VAT Number'
            );

            $installer->getConnection()->createTable($table);
        }

        $installer->endSetup();
    }
}

Step 6: Save the Data

Ensure that the captured data from the form is saved accurately into the relevant tables.

Step 7: Test Your Customization

After implementing the code, test the functionality on the frontend. Make sure the VAT number field appears only when the checkbox is checked and that the data is saved in the database.

Conclusion

By following these detailed steps, you can successfully add a custom checkbox that conditionally displays the VAT number field on the Magento 2 Shipping Page. This enhancement will not only improve user experience but also bolster data management and compliance. Customizing Magento 2 in this manner requires attention to detail and a careful approach to ensure seamless functionality and integration.

FAQ

Why is this customization important?

This customization ensures that you capture necessary VAT information only when required, maintaining a clean and user-friendly checkout interface.

Do I need coding knowledge to implement this?

Yes, you need a basic understanding of Magento 2's structure, PHP, and XML.

What versions of Magento does this apply to?

This guide is applicable for Magento versions 2.4.2 through 2.4.6, but with minor adjustments, it can be adapted for other versions.

Can I use this customization for other fields?

Yes, the logic applied here can be extended to other custom fields as required.

By following this guide, you're equipped to enhance your Magento 2 store with a sophisticated, user-friendly customization that meets both usability and compliance standards.