Abbas
Abbas

Reputation: 781

Magento2 Custom attribute is not saving during customer registration from frontend

I am trying to add the custom attribute to registration form. And i have added the attribute successfully by the following code

class InstallData implements InstallDataInterface
{
    /**
     * @var EavSetupFactory Magento\Eav\Setup\EavSetupFactory
     */
    private $eavSetupFactory;

    /**
     * @var $_eavConfig Config
     */
    protected $eavConfig;

    public function __construct(EavSetupFactory $eavSetupFactory, Config $eavConfig)
    {
        $this->eavSetupFactory = $eavSetupFactory;
        $this->eavConfig = $eavConfig;
    }

    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);

        $eavSetup->addAttribute(
            \Magento\Customer\Model\Customer::ENTITY,
            'mobile',
            [
                'type' => 'varchar',
                'label' => 'Mobile',
                'input' => 'text',
                'required' => false,
                'system' => false,
                'position' => 100,
                'visible' => true,
                'user_defined' => true
            ]
        );
        $mobile = $this->eavConfig->getAttribute(\Magento\Customer\Model\Customer::ENTITY, 'mobile');
        //$forms = ['adminhtml_customer', 'checkout_register', 'customer_account_create', 'customer_account_edit'];
        $forms = ['adminhtml_customer'];
        $mobile->setData(
            'used_in_forms',
            $forms
        );
        $mobile->save();
    }
}

And to show at front-end i am using the layout handler customer_account_create with the following code

 <referenceContainer name="form.additional.info">
            <block class="Namespace\SMS\Block\Active" name="sms_block">
                <action method="setTemplate" ifconfig="sms/actions/register" ifvalue="1">
                    <argument name="template" xsi:type="string">Namespace_SMS::sms/register.phtml</argument>
                </action>
            </block>
        </referenceContainer>

Now it is showing the mobile field during registration. But when i try to create account mobile field value is empty after create account.

Note: I know if i add the 'customer_account_create', 'customer_account_edit' with used_in_form then mobile value save. But after this i can not use a specific template file to render mobile field.

Can you please let me know how can i solve this issue? Thank you very much.

Upvotes: 0

Views: 9297

Answers (2)

PЯINCƎ
PЯINCƎ

Reputation: 724

IF someone is looking for the solution, nearly to the @Abbas answer, but modified in observer part:

<?php 

namespace {Vendor}\Module\Observer;

use Magento\Framework\Event\Observer as EventObserver;
use Magento\Framework\Event\ObserverInterface;

class CustomerRegisterObserver implements ObserverInterface
{
    /**
     * @var \Magento\Customer\Model\CustomerFactory
     */
    protected $_customerFactory;
    protected $_customerRepository;

    function __construct(
        \Magento\Customer\Model\CustomerFactory $customerFactory,
        \Psr\Log\LoggerInterface $logger
    ) {
        $this->_customerFactory = $customerFactory;
        $this->_logger = $logger;
    }


    public function execute(EventObserver  $observer)
    {
        //$this->_logger->info("Observer CustomerRegisterObserver Loaded !");
        $event = $observer->getEvent();
        $customerData = $event->getCustomer();

        if($_POST['mobile']) {
            $customer = $this->_customerFactory->create()->load($customerData->getId());
            $customer->setData('mobile', $_POST['mobile']);
            $customer->save();
        }
    }
}

Upvotes: 0

Abbas
Abbas

Reputation: 781

I do not know whether it is 100% correct according to the coding rules. But I have resolved this issue using the observer and little bit changes in InstallData script.

InstallData.php is like this

class InstallData implements InstallDataInterface
{
    /**
     * Customer setup factory
     *
     * @var \Magento\Customer\Setup\CustomerSetupFactory
     */
    private $customerSetupFactory;

    /**
     * Init
     *
     * @param \Magento\Customer\Setup\CustomerSetupFactory $customerSetupFactory
     */
    public function __construct(\Magento\Customer\Setup\CustomerSetupFactory $customerSetupFactory) {
        $this->customerSetupFactory = $customerSetupFactory;
    }


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

        /** @var CustomerSetup $customerSetup */
        $customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);


        $customerSetup->addAttribute(
            \Magento\Customer\Model\Customer::ENTITY,
            'mobile',
            [
                'type' => 'varchar',
                'label' => 'Mobile',
                'input' => 'text',
                'required' => false,
                'system' => false,
                'position' => 100,
                'visible' => true,
                'user_defined' => true
            ]
        );

        $customerSetup->updateAttribute('customer', 'mobile', 'is_used_for_customer_segment', '1');

        //$forms = ['adminhtml_customer', 'checkout_register', 'customer_account_create', 'customer_account_edit'];
        $forms = ['adminhtml_customer'];

        $attribute = $customerSetup->getEavConfig()->getAttribute('customer', 'mobile');
        $attribute->setData('used_in_forms', ['adminhtml_customer']);
        $attribute->addData([
            'attribute_set_id' => 1,
            'attribute_group_id' => 1
        ]);
        $attribute->save();
        $setup->endSetup();
    }
}

then events.xml is like this

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="customer_register_success">
        <observer name="sMSHandleCustomerSaveAfter" instance="\Namepace\SMS\Observer\CustomerRegisterObserver" />
    </event>

</config>

And the observer is like this

class CustomerRegisterObserver implements ObserverInterface
{

    /**
     * @var \Magento\Customer\Model\CustomerFactory
     */
    protected $_customerFactory;

    function __construct(CustomerFactory $customerFactory)
    {
        $this->_customerFactory = $customerFactory;

    }


    public function execute(Observer $observer)
    {
        $customerData = $observer->getCustomer();
        if($_POST['mobile']) {
            $customer = $this->_customerFactory->create()->load($customerData->getId());
            $customer->setData('mobile', $_POST['mobile']);
            $customer->save();
        }
    }
}

Upvotes: 1

Related Questions