Here we will learn, how to create customer attribute without using installer in magento 2.
Note: We also have a separate module (Magento 2 Custom Registration Fields) that allows the admin to create custom fields for customers. Henceforth, using this module you can extend your customer sign-up form. For more information, you can check it on our store.
Let’s start the process.
To know steps to create module in Magento2, you can check our another blog here.
1) Create a controller file: Webkul/CustomerAttribute/Controller/Attribute/Save.php
<?php namespace Webkul\CustomerAttribute\Controller\Attribute; use Magento\Framework\App\Action\Action; use Magento\Framework\App\Action\Context; use Magento\Eav\Setup\EavSetupFactory; use Magento\Eav\Setup\EavSetup; use Magento\Eav\Model\Config; use Magento\Framework\Setup\ModuleDataSetupInterface; use Magento\Customer\Setup\CustomerSetupFactory; class Save extends Action { /** * @var \Magento\Framework\Stdlib\DateTime\DateTime */ protected $_moduleDataSetup; /** * @var CustomerSetupFactory */ protected $_customerSetupFactory; protected $_eavSetup; protected $_eavConfig; /** * @var AttributeMetadataDataProvider */ private $_attributeMetaData; /** * @param Context $context * @param ModuleDataSetupInterface $moduleDataSetup * @param CustomerSetupFactory $customerSetupFactory * @param EavSetup $eavSetup * @param Config $eavConfig */ public function __construct( Context $context, ModuleDataSetupInterface $moduleDataSetup, CustomerSetupFactory $customerSetupFactory, EavSetup $eavSetup, Config $eavConfig ) { $this->_moduleDataSetup = $moduleDataSetup; $this->_customerSetupFactory = $customerSetupFactory; $this->_eavSetup = $eavSetup; $this->_eavConfig = $eavConfig; parent::__construct($context); } /** * Save action. * * @return \Magento\Framework\Controller\ResultInterface */ public function execute() { /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultRedirectFactory->create(); $customerSetup = $this->_customerSetupFactory->create(['setup' => $this->_moduleDataSetup]); $customerEntity = $customerSetup->getEavConfig()->getEntityType('customer'); $customer = $this->_eavSetup->getEntityTypeId('customer'); $attributeSetId = $customerEntity->getDefaultAttributeSetId(); $attributeGroupId = $customerEntity->getDefaultGroupId($attributeSetId); /* * Creating Custom Customer Attribute */ $attribute = $this->_eavConfig->getAttribute('customer', 'custom_attribute_test'); $attribute->addData([ 'frontend_type' => 'varchar', 'backend_type' => 'varchar', 'frontend_label' => 'Custom Attribute Test', 'frontend_input' => 'text', 'frontend_class' => '', 'sort_order' => 1000, 'is_visible' => 0, 'is_system' => false, 'is_user_defined' => true, 'position' => 1000, 'attribute_set_id' => $attributeSetId, 'attribute_group_id' => $attributeGroupId, 'used_in_forms' => ['adminhtml_customer'], ]); $attribute->save(); return $resultRedirect->setPath('*/*/'); } }
Be the first to comment.