How to insert custom elements to customer programmatically in Magento 2

How to insert custom elements to customer programmatically in Magento 2?

In this topic I will show you how to insert custom elements to customer programmatically

  • First you need to create file InstallData.php in your setup folder:
app/code/Webnexs/Example/Setup/InstallData.php
<?

namespaceWebnexs\Example\Setup;

use Magento\Eav\Setup\EavSetup;

use Magento\Eav\Setup\EavSetupFactory;

use Magento\Framework\Setup\InstallDataInterface;

use Magento\Framework\Setup\ModuleContextInterface;

use Magento\Framework\Setup\ModuleDataSetupInterface;

 class InstallData implements InstallDataInterface

{

private $eavSetupFactory;

public function __construct(EavSetupFactory $eavSetupFactory)

{

$this->eavSetupFactory = $eavSetupFactory;

}

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

{

$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);

$eavSetup->addAttribute(

\Magento\Customer\Model\Customer::ENTITY,

'custom_attribute',

[

'type' => 'int',

'label' => Label Of Attribute',

'required' => false,

'default' =>  null

'input' => 'select',

'source' => 'Magento\Eav\Model\Entity\Attribute\Source\Boolean', ]

);

$customAttribute = $this->eavConfig->getAttribute(\Magento\Customer\Model\Customer::ENTITY, 'custom_attribute');

$customAttribute>setData(

'used_in_forms',

['adminhtml_customer_address', 'customer_address_edit', 'customer_register_address']

);

$customAttribute>save();

}

}
  • Then you need to open SSH and run command : php magento setup: upgrade
  • Clear cache : php magento cache: flush

I hope the following step is the simplest process for you to insert custom elements to customer programmatically in Magento 2. With this guide you can manage the custom elements in Magento 2 is effortlessly. All stores has a custom elements in Magento 2 with multiple elements

Last Update: April 9, 2018  

February 14, 2018   159   Nandini R    Tips And Tricks    
Total 1 Votes:
0

Tell us how can we improve this post?

+ = Verify Human or Spambot ?

Leave a Reply

Your email address will not be published. Required fields are marked *

Facebook
Google+
http://www.webnexs.com/blog/kb/insert-custom-elements-customer-programmatically
Twitter
LinkedIn