3

I am adding customer attribute in magento 2

$customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);
        $customerEntity = $customerSetup->getEavConfig()->getEntityType('customer');
        $attributeSetId = $customerEntity->getDefaultAttributeSetId();

        /** @var $attributeSet AttributeSet */
        $attributeSet = $this->attributeSetFactory->create();
        $attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);

        $customerSetup->addAttribute(\Magento\Customer\Model\Customer::ENTITY, 'test', [
            'type' => 'varchar',
            'label' => 'Test',
            'input' => 'text',
            'required' => true,
            'visible' => true,
            'user_defined' => true,
            'sort_order' => 90,
            'position' => 90,
            'system' => 0,
        ]);

        $attribute = $customerSetup->getEavConfig()->getAttribute(\Magento\Customer\Model\Customer::ENTITY, 'test')
            ->addData([
                'attribute_set_id' => $attributeSetId,
                'attribute_group_id' => $attributeGroupId,
                'used_in_forms' => ['adminhtml_customer','customer_account_create'],
            ]);

        $attribute->save();

add in register.phtml

<div class="field test">
            <label for="test" class="label"><span><?php /* @escapeNotVerified */ echo __('Test') ?></span></label>
            <div class="control">
                <input type="text" name="test" id="test" value="<?php echo $block->escapeHtml($block->getFormData()->getTest()) ?>" title="<?php /* @escapeNotVerified */ echo __('Test') ?>" class="input-text">
            </div>
        </div>

and now when i add values in form for register it gives me an error

"Test" is a required value

What to do? i can't understand

1 Answer 1

0

Change required=>true to required=>false

$customerSetup->addAttribute(\Magento\Customer\Model\Customer::ENTITY, 'test', [
        'type' => 'varchar',
        'label' => 'Test',
        'input' => 'text',
        'required' => false,//Change here
        'visible' => true,
        'user_defined' => true,
        'sort_order' => 90,
        'position' => 90,
        'system' => 0,
    ]);
6
  • 3
    i want this attribute as require field
    – ND17
    Dec 6, 2016 at 9:58
  • when "Test" is a required value error message comes? Dec 6, 2016 at 10:01
  • I want attribute as require field and when i am submit form and it redirect to registration page and show this error
    – Newbie
    Dec 6, 2016 at 10:08
  • have you entered any text in that field or without its you an give error? Dec 6, 2016 at 10:15
  • of course! I enter text in that field
    – Newbie
    Dec 6, 2016 at 10:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.