3

In Magento 2 CE we have to add new attributes with Coding? It's not provided by default?

I have looked in to http://www.extensions.sashas.org/blog/magento-2-make-customer-attribute.html

I would like to add custom customer attribute called "passport" in Magento 2 CE.

I also like to apply validation of that on both side client & server. Through jQuery regexp we can achieve this. But the main concern is where to add/in which file so it will not affect other things

2

4 Answers 4

4

Place this code in InstallData Script in custom module.

InstallData.php

namespace Paarth\CustomerAttribute\Setup;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
class InstallData implements InstallDataInterface
{ 

    private $customerSetupFactory;      

    public function __construct(\Magento\Customer\Setup\CustomerSetupFactory $customerSetupFactory)
    {
      $this->customerSetupFactory = $customerSetupFactory;
    }

    public function install(ModuleDataSetupInterface
    $setup, ModuleContextInterface $context)
    {
        /** @var CustomerSetup $customerSetup */

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

        $attributeCode = "passport";

        $customerSetup->removeAttribute(\Magento\Customer\Model\Customer::ENTITY, $attributeCode);          

        $customerSetup->addAttribute('customer',
        'passport', [
        'label' => 'Passport',
        'type' => 'text',
        'frontend_input' => 'text',
        'required' => false,
        'visible' => true,
         'system'=> 0,
        'position' => 105,
        ]);

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

        $setup->endSetup();
    }
}
6
  • Added @Paarth. Not working. Not showing in DB as well :(. Internal messages between users not allowed.
    – Jackson
    Aug 10, 2016 at 6:13
  • Did you change namespace ?
    – Sourav
    Aug 11, 2016 at 4:19
  • Nope. I think tutorial only missing registration.php file. So i have added that & it works well. Thank you for help & effort at well. Appreciated :)
    – Jackson
    Aug 11, 2016 at 4:23
  • Thanks Mike. can you send me skype Id or email address.
    – Sourav
    Aug 11, 2016 at 4:24
  • There is no internal messaging system. How to do it?
    – Jackson
    Aug 11, 2016 at 5:44
0

Use $customerSetup (solution by @Paarth) and add 'adminhtml_only' => true as a part of attribute configuration instead of

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

You can also add 'is_used_in_grid' => true if you want it to be available in grid

0
<?php

namespace Eg\Solution\Setup;

use Magento\Customer\Api\CustomerMetadataInterface;
use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\UpgradeDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Eav\Model\Config;
use Magento\Customer\Model\Customer;

class UpgradeData implements UpgradeDataInterface
{
    private $eavSetupFactory;

    public function __construct(EavSetupFactory $eavSetupFactory, Config $eavConfig)
    {
        $this->eavSetupFactory = $eavSetupFactory;
        $this->eavConfig       = $eavConfig;
    }

    public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
        $eavSetup->addAttribute(
            \Magento\Customer\Model\Customer::ENTITY,
            'loyal_customer',
            [
                'type'         => 'int',
                'label'        => 'Loyal Customer',
                'input'        => 'boolean',
                'source' => 'Magento\Eav\Model\Entity\Attribute\Source\Boolean',
                'global' => 'Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL',
                'required'     => false,
                'visible'      => true,
                'user_defined' => true,
                'position'     => 999,
                'system'       => 0,
            ]
        );
            $eavSetup->addAttributeToSet(
                CustomerMetadataInterface::ENTITY_TYPE_CUSTOMER,
                CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
                null,
                'loyal_customer');
        $sampleAttribute = $this->eavConfig->getAttribute(Customer::ENTITY, 'loyal_customer');

        // more used_in_forms ['adminhtml_checkout','adminhtml_customer','adminhtml_customer_address','customer_account_edit','customer_address_edit','customer_register_address']
        $sampleAttribute->setData(
            'used_in_forms',
            ['adminhtml_customer']

        );
        $sampleAttribute->getResource()->save($sampleAttribute);
    }
}
-1

First of all create a sample module called Mageplaza_HelloWorld and the InstallDataclass.

then,create InstallData.php file

on app/code/Mageplaza/Example/Setup/InstallData.php

<?php
namespace Mageplaza\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;
    }

}

In this class, we define the EAV setup model which will be use to interact with Magento 2 attribute.

After that, we have to define the install() method and create eav setup model:

public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
    }
    Next, we will use eavSetup object to add attribute:
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
        $eavSetup->addAttribute(
            \Magento\Customer\Model\Customer::ENTITY,
            'sample_attribute',
            [
                'type' => 'int',
                'label' => 'Sample Attribute',
                'input' => 'select',
                'source' => 'Magento\Eav\Model\Entity\Attribute\Source\Boolean',
                'required' => true,
                'default' => '0',
                'sort_order' => 100,
                'system' => false,
                'position' => 100
            ]
        );
}

Finally, we need to set the forms in which the attributes will be used. In this step, we need define the eavConfig object which allow us to call the attribute back and set the data for it. And the full code to create customer attribute is:

File: app/code/Mageplaza/Example/Setup/InstallData.php

<?php
namespace Mageplaza\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;
use Magento\Eav\Model\Config;

class InstallData implements InstallDataInterface
{
    private $eavSetupFactory;

    public function __construct(EavSetupFactory $eavSetupFactory, Config $eavConfig)
    {
        $this->eavSetupFactory = $eavSetupFactory;
        $this->eavConfig = $eavConfig;
    }

    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
        $eavSetup->addAttribute(
            \Magento\Customer\Model\Customer::ENTITY,
            'sample_attribute',
            [
                'type' => 'int',
                'label' => 'Sample Attribute',
                'input' => 'select',
                'source' => 'Magento\Eav\Model\Entity\Attribute\Source\Boolean',
                'required' => true,
                'default' => '0',
                'sort_order' => 100,
                'system' => false,
                'position' => 100
            ]
        );
        $sampleAttribute = $this->eavConfig->getAttribute(\Magento\Customer\Model\Customer::ENTITY, 'sample_attribute');
        $sampleAttribute->setData(
            'used_in_forms',
            ['adminhtml_customer_address', 'customer_address_edit', 'customer_register_address']
        );
        $sampleAttribute->save();
    }
}

Now, let run command line to install the module: php magento setup:upgrade. Then check the customer page to see the new attribute.

I hope it helps you !!

3
  • this also didn't helped Oct 30, 2018 at 10:34
  • This answer was blatantly plagiarised from the top post on google and is in essence the same method as an earlier, neater answer. Sep 12, 2019 at 15:39
  • I used following extension github.com/diglin/Diglin_Username2 And it is just working fine. I want to update/set the custom attribute of customer value programmatically & save it in database. This is not working. Can you suggest me some technique/procedure to achieve this.... Feb 28, 2020 at 15:55

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