Jump to content


JiMMy2021's Content

There have been 1 items by JiMMy2021 (Search limited from 28-September 23)


By content type

See this member's

Sort by                Order  

#21638 How to Add Custom Customer Attribute in Registration Form in Magento 2

Posted by JiMMy2021 on 23 July 2021 - 03:57 PM in Magento general discussions

Hello,

 

I have created a custom attribute for customer in Magento 2 site.

 

The HTML template of the field is this:

<input type="text"
name="<?= $block->escapeHtmlAttr($block->getFieldName('custom')) ?>"
id="custom"
value="<?= $block->escapeHtmlAttr($block->getObject()->getCustom()) ?>"
title="<?= $block->escapeHtmlAttr($block->getAttributeData()->getFrontendLabel('custom')) ?>"
class="input-text"
data-validate="{required:true, 'validateData':true}">

Look at all `$block` calls. None of them works.

 

`$block->getFieldName('custom')` returns an empty string

 

`$block->getObject()->getCustom()` throws an exception because `getObject` is null

 

`$block->getAttributeData()->getFrontendLabel('custom')` throws an exception because `$block->getAttributeData()` is null.

 

How can I keep the value the user has entered in the custom field when page is reloaded?

 

The field value is something that should be retrieved dynamically, because if there is an error in the registration form, and the page is reloaded, all fields should be repopulated. This works for all standard fields but not for the custom ones.

 

This is how I an creating the attribute:

public function addCustomAttribute()
    {
        $eavSetup = $this->eavSetupFactory->create();


        $eavSetup->addAttribute(
            \Magento\Customer\Model\Customer::ENTITY,
            'custom',
            [
                'type' => 'varchar',
                'label' => 'My label',
                'input' => 'text',
                'required' => 1,
                'visible' => 1,
                'user_defined' => 1,
                'sort_order' => 1,
                'position' => 1,
                'system' => 0,
                'is_used_in_grid' => true,
                'is_visible_in_grid' => true,
                'is_filterable_in_grid' => true,
                'is_searchable_in_grid' => true,
            ]
        );

        $attributeSetId = $eavSetup->getDefaultAttributeSetId(Customer::ENTITY);
        $attributeGroupId = $eavSetup->getDefaultAttributeGroupId(Customer::ENTITY);

        $attribute = $this->eavConfig->getAttribute(Customer::ENTITY, 'custom');
        $attribute->setData('attribute_set_id', $attributeSetId);
        $attribute->setData('attribute_group_id', $attributeGroupId);

        $attribute->setData('used_in_forms', [
            'adminhtml_checkout',
            'adminhtml_customer',
            'customer_account_create',
            'customer_account_edit',
            'checkout_index_index'
        ]);

        $this->attributeResource->save($attribute);
    }

Any help, please?