Question

I need to make lastname optional in customer registration form.

Was it helpful?

Solution

First of all you should remove the is_required option from the lastname attributes in the customer entity and address entity:

UPDATE `eav_attribute` SET `is_required`=0 WHERE `attribute_code`='lastname'

Then you should rewrite registration form of your theme. In the default magento setup this template is located here:

vendor/magento/module-customer/view/frontend/templates/widget/name.phtml

You should remove validation and required class from the lastname label and lastname input, like:

<div class="field field-name-lastname">
    <label class="label"  for="<?php /* @escapeNotVerified */ echo $block->getFieldId('lastname') ?>">
        <span><?php /* @escapeNotVerified */ echo $block->getStoreLabel('lastname') ?></span>
    </label>

    <div class="control">
        <input type="text" id="<?php /* @escapeNotVerified */ echo $block->getFieldId('lastname') ?>"
               name="<?php /* @escapeNotVerified */ echo $block->getFieldName('lastname') ?>"
               value="<?php echo $block->escapeHtml($block->getObject()->getLastname()) ?>"
               title="<?php /* @escapeNotVerified */ echo $block->getStoreLabel('lastname') ?>"
               class="input-text <?php /* @escapeNotVerified */ echo $block->getAttributeValidationClass('lastname') ?>" <?php /* @escapeNotVerified */ echo $block->getFieldParams() ?>>
    </div>
</div>

Important Note: Do not change the original file! You should do it in a custom module or theme!

OTHER TIPS

I think that it would be better to update the

is_required

option through upgrade script instead of run a query directly on database.

You should create in your module an UpgradeData.php in this path

app/code/Vendor/Module/Setup

and put inside this code

<?php

namespace Vendor\Module\Setup;

use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Customer\Model\Customer;
use Magento\Customer\Setup\CustomerSetupFactory;

class UpgradeData implements \Magento\Framework\Setup\UpgradeDataInterface
{
    private $customerSetupFactory;

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

    public function upgrade(ModuleDataSetupInterface $setup,
                            ModuleContextInterface $context)
    {
        $setup->startSetup();

        if (version_compare($context->getVersion(), '1.0.1', '<=')) {
            $customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);
            $customerSetup->updateAttribute(Customer::ENTITY, 'lastname', 'is_required', 0);
        }

        $setup->endSetup();
    }
}

Then run bin/magento setup:upgrade to apply to database

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top