How to Add Custom Attribute to Customer Programmatically?
This post will guide you how to create customer custom attribute in Magento 2.0.x programatically.Firstly, you need create file InstallData.php in your setup folder:
Create file: app/code/AGM/Exercise/Setup/InstallData.php
Insert code as below and change your attribute name.
<?php namespace AGM\Exercise\Setup; use Magento\Customer\Setup\CustomerSetupFactory; use Magento\Customer\Model\Customer; use Magento\Eav\Model\Entity\Attribute\Set as AttributeSet; use Magento\Eav\Model\Entity\Attribute\SetFactory as AttributeSetFactory; use Magento\Framework\Setup\InstallDataInterface; use Magento\Framework\Setup\ModuleContextInterface; use Magento\Framework\Setup\ModuleDataSetupInterface; class InstallData implements InstallDataInterface { /** * @var customerSetupFactory */ protected $customerSetupFactory; /** * @var attributeSetFactory */ private $attributeSetFactory; /** * @param CustomerSetupFactory $customerSetupFactory * @param AttributeSetFactory $attributeSetFactory */ public function __construct( CustomerSetupFactory $customerSetupFactory, AttributeSetFactory $attributeSetFactory ) { $this->customerSetupFactory = $customerSetupFactory; $this->attributeSetFactory = $attributeSetFactory; } 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, 'custom_attribute_name', [ 'type' => 'varchar', 'label' => 'Custom Attribute', 'input' => 'text', 'required' => true, 'visible' => true, 'user_defined' => true, 'system' => 0, ]); $attribute = $customerSetup->getEavConfig()->getAttribute(Customer::ENTITY, 'custom_attribute_name') ->addData([ 'attribute_set_id' => $attributeSetId, 'attribute_group_id' => $attributeGroupId, 'used_in_forms' => ['adminhtml_customer'],//use below to add into other form ['adminhtml_customer_address', 'customer_address_edit', 'customer_register_address'] ]); $attribute->save(); } }
Now, let run below command and then check the result.
php magento setup:upgrade
php bin/magento setup:static-content:deploy
Thank you for reading this post hope this helps you!
Comments
Post a Comment