1

I want to add extra fields for customer (not on registration) where there should around 20 fields. We can do this easily in magento 1 but i didn't see any thing same in M2.

looking for guidance and if this can be achieved from admin that would be great.

1 Answer 1

1

This article describe it step by step:
http://www.extensions.sashas.org/blog/magento-2-make-customer-attribute.html

The main part is DataInstall::install method:

public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context) {

    /** @var CustomerSetup $customerSetup */
    $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(Customer::ENTITY, '{attributeCode}', [
        'type' => 'varchar',
        'label' => '{attributeLabel}',
        'input' => 'text',
        'required' => false,
        'visible' => true,
        'user_defined' => true,
        'sort_order' => 1000,
        'position' => 1000,
        'system' => 0,
    ]);
    //add attribute to attribute set
    $attribute = $customerSetup->getEavConfig()->getAttribute(Customer::ENTITY, 'magento_username')
    ->addData([
        'attribute_set_id' => $attributeSetId,
        'attribute_group_id' => $attributeGroupId,
        'used_in_forms' => ['adminhtml_customer'],
    ]);

    $attribute->save();


}

Or a bit slighter:

$customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);

$customerSetup->addAttribute(
    \Magento\Customer\Model\Customer::ENTITY,
    'nickname',
    [
        'label'            => 'Nickname',
        'required'         => 0,
        'system'           => 0,
        'position'         => 100
    ]
);

$customerSetup->getEavConfig()->getAttribute('customer', 'nickname')
    ->setData('used_in_forms', ['adminhtml_customer'])
    ->save();

Also here is nice article:
https://www.atwix.com/magento/adding-attribute-programatically-magento2/

2
  • It mean option M2 is missing adding customer attributes like M1. Thanks for your reply and I am going to work on your response.
    – Sharma
    Mar 30, 2017 at 9:10
  • Yea, there is no option for create it from admin. let me know if it works for You:) Mar 30, 2017 at 9:16

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.