Question

With pre-2.3 Magento versions we were able to write UpgradeData code and make customer's lastname optional as mentioned here: Magento 2 : How to make “lastname ” optional in customer registration form? .

How I can make customer's lastname optional using declarative schema approach?

Was it helpful?

Solution

Magento 2.3 has introduced Data Patch classes which contains data modification instructions.

If you want to update existing table data, you can create a datapatch class at Vendor/Module/Setup/Patch/Data/<Data_Patch_Class>.php and make the required modification there.

To make customer's lastname optional I have used following code:

<?php

namespace Vendor\Module\Setup\Patch\Data;

use Magento\Customer\Setup\CustomerSetupFactory;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\Patch\DataPatchInterface;

class LastnameOptional implements DataPatchInterface
{
    /**
     * @var CustomerSetupFactory
     */
    private $customerSetupFactory;
    /**
     * @var ModuleDataSetupInterface
     */
    private $moduleDataSetup;

    public function __construct(
        CustomerSetupFactory $customerSetupFactory,
        ModuleDataSetupInterface $moduleDataSetup
    ) {
        $this->customerSetupFactory = $customerSetupFactory;
        $this->moduleDataSetup = $moduleDataSetup;
    }

    public static function getDependencies()
    {
        return [];
    }

    public function getAliases()
    {
        return [];
    }

    public function apply()
    {
        $customerSetup = $this->customerSetupFactory->create(['resourceConnection' => $this->moduleDataSetup]);
        $customerSetup->updateAttribute('customer', 'lastname', 'is_required', 0);
        $customerSetup->updateAttribute('customer_address', 'lastname', 'is_required', 0);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top