/   /   /  Magento 2 Add custom EAV attribute to category or customer (support 2.1 too and higher)

Note:

For more extensions and themes visit our store

Magento 2 Add custom EAV attribute to category or customer (support 2.1 too and higher)

EAV system in Magento 2 almost similar to Magento 1 but many function and technique is changed , in this tutorials we give you 2 example of how adding custom eav attribute to category or customer .

Download or Explore  code example in github

1 – Create custom attribute for category :
 A - For Magento 2.1 and higher

Go to your model and create Setup folder , inside it create file InstallData.php and push this full code :

  1.  
  2. <?php
  3. /**
  4.  * Copyright © 2015 Magento. All rights reserved.
  5.  * See COPYING.txt for license details.
  6.  */
  7. namespace Ibnab\CustomAttribute\Setup;
  8. use Magento\Framework\Module\Setup\Migration;
  9. use Magento\Framework\Setup\InstallDataInterface;
  10. use Magento\Framework\Setup\ModuleContextInterface;
  11. use Magento\Framework\Setup\ModuleDataSetupInterface;
  12. use Magento\Catalog\Setup\CategorySetupFactory;
  13.  
  14. /**
  15.  * @codeCoverageIgnore
  16.  */
  17. class InstallData implements InstallDataInterface
  18. {
  19.     /**
  20.      * Category setup factory
  21.      *
  22.      * @var CategorySetupFactory
  23.      */
  24.     private $categorySetupFactory;
  25.  
  26.     /**
  27.      * Init
  28.      *
  29.      * @param CategorySetupFactory $categorySetupFactory
  30.      */
  31.     public function __construct(CategorySetupFactory $categorySetupFactory)
  32.     {
  33.         $this->categorySetupFactory = $categorySetupFactory;
  34.     }
  35.     /**
  36.      * {@inheritdoc}
  37.      * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  38.      */
  39.     public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
  40.     {
  41.         $installer = $setup;
  42.          $installer->startSetup();
  43.  
  44.         $categorySetup = $this->categorySetupFactory->create(['setup' => $setup]);
  45.         $entityTypeId = $categorySetup->getEntityTypeId(\Magento\Catalog\Model\Category::ENTITY);
  46.         $attributeSetId = $categorySetup->getDefaultAttributeSetId($entityTypeId);
  47.          $categorySetup->removeAttribute(
  48.         \Magento\Catalog\Model\Category::ENTITY, 'my_attribute' );
  49.         $categorySetup->addAttribute(
  50.         \Magento\Catalog\Model\Category::ENTITY, 'my_attribute', [
  51.              'type' => 'int',
  52.              'label' => 'My Atrribute ',
  53.              'input' => 'select',
  54.              'source' => 'Magento\Eav\Model\Entity\Attribute\Source\Boolean',
  55.              'required' => false,
  56.              'sort_order' => 100,
  57.              'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_STORE,
  58.              'group' => 'General Information',
  59.         ]
  60.     );
  61. $installer->endSetup();
  62.     }
  63. }
  64.  
  65.  

After that you need add category_form.xml inside view/adminhtml/ui_component inside your module and push:

  1. </span>
  2. <?xml version="1.0" encoding="UTF-8"?>
  3. <!--
  4. /**
  5.  * Copyright © 2016 Magento. All rights reserved.
  6.  * See COPYING.txt for license details.
  7.  */
  8. -->
  9. <form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  10.       xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
  11.     <fieldset name="general">
  12.         <field name="my_attribute">
  13.             <argument name="data" xsi:type="array">
  14.             <item name="options" xsi:type="object">Magento\Config\Model\Config\Source\Yesno</item>
  15.                 <item name="config" xsi:type="array">
  16.                     <item name="sortOrder" xsi:type="number">60</item>
  17.                     <item name="dataType" xsi:type="string">string</item>
  18.                     <item name="formElement" xsi:type="string">select</item>
  19.                     <item name="label" xsi:type="string" translate="true">My Attribute </item>
  20.                 </item>
  21.             </argument>
  22.         </field>    
  23.     </fieldset>
  24. </form>
  25. <span style="line-height:13px">
  26.  

 

B - For Magento 2.07and  lower

  1. </span><br style="line-height: 13px;" />
  2. <?php
  3. /**
  4.  * Copyright © 2015 Magento. All rights reserved.
  5.  * See COPYING.txt for license details.
  6.  */
  7. namespace Ibnab\CustomAttribute\Setup;
  8. use Magento\Framework\Module\Setup\Migration;
  9. use Magento\Framework\Setup\InstallDataInterface;
  10. use Magento\Framework\Setup\ModuleContextInterface;
  11. use Magento\Framework\Setup\ModuleDataSetupInterface;
  12. use Magento\Catalog\Setup\CategorySetupFactory;
  13.  
  14. /**
  15.  * @codeCoverageIgnore
  16.  */
  17. class InstallData implements InstallDataInterface
  18. {
  19.     /**
  20.      * Category setup factory
  21.      *
  22.      * @var CategorySetupFactory
  23.      */
  24.     private $categorySetupFactory;
  25.  
  26.     /**
  27.      * Init
  28.      *
  29.      * @param CategorySetupFactory $categorySetupFactory
  30.      */
  31.     public function __construct(CategorySetupFactory $categorySetupFactory)
  32.     {
  33.         $this->categorySetupFactory = $categorySetupFactory;
  34.     }
  35.     /**
  36.      * {@inheritdoc}
  37.      * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  38.      */
  39.     public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
  40.     {
  41.         $installer = $setup;
  42.          $installer->startSetup();
  43.  
  44.         $categorySetup = $this->categorySetupFactory->create(['setup' => $setup]);
  45.         $entityTypeId = $categorySetup->getEntityTypeId(\Magento\Catalog\Model\Category::ENTITY);
  46.         $attributeSetId = $categorySetup->getDefaultAttributeSetId($entityTypeId);
  47.          $categorySetup->removeAttribute(
  48.         \Magento\Catalog\Model\Category::ENTITY, 'my_attribute');
  49.         $categorySetup->addAttribute(
  50.         \Magento\Catalog\Model\Category::ENTITY, 'my_attribute', [
  51.              'type' => 'int',
  52.              'label' => 'My Atrribute ',
  53.              'input' => 'select',
  54.              'source' => 'Magento\Eav\Model\Entity\Attribute\Source\Boolean',
  55.              'required' => false,
  56.              'sort_order' => 100,
  57.              'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_STORE,
  58.              'group' => 'General Information',
  59.         ]
  60.     );
  61.     $idg =  $categorySetup->getAttributeGroupId($entityTypeId, $attributeSetId, 'General Information');
  62.     $categorySetup->addAttributeToGroup(
  63.         $entityTypeId,
  64.         $attributeSetId,
  65.         $idg,
  66.         'my_attribute',
  67.         46
  68.     );
  69. $installer->endSetup();
  70.     }
  71. }<br style="line-height: 13px;" />
  72. <span style="line-height:13px">
  73.  

 

in this code we injected Magento\Catalog\Setup\CategorySetupFactory and get instance of category setup object with :

  1.  
  2.  $categorySetup = $this->categorySetupFactory->create(['setup' => $setup]);
  3.  
  4.  

after that we get the entity type id and atrribute set id :

  1.  
  2. $entityTypeId = $categorySetup->getEntityTypeId(\Magento\Catalog\Model\Category::ENTITY);
  3. $attributeSetId = $categorySetup->getDefaultAttributeSetId($entityTypeId);
  4.  
  5.  

first we remove if exist :

  1.  
  2. $categorySetup->removeAttribute(
  3.         \Magento\Catalog\Model\Category::ENTITY, 'my_attribute',
  4.     );
  5.  
  6.  

the \Magento\Catalog\Model\Category::ENTITY is static variable from category model :

  1.  
  2. const ENTITY = 'catalog_category';
  3.  
  4.  

and we add our custom attribute with type field select :
const ENTITY = 'catalog_category';

and we add our custom attribute with type field select :

  1.  
  2.         $categorySetup->addAttribute(
  3.         \Magento\Catalog\Model\Category::ENTITY, 'my_attribute', [
  4.              'type' => 'int',
  5.              'label' => 'My Atrribute ',
  6.              'input' => 'select',
  7.              'source' => 'Magento\Eav\Model\Entity\Attribute\Source\Boolean',
  8.              'required' => false,
  9.              'sort_order' => 100,
  10.              'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_STORE,
  11.              'group' => 'General Information',
  12.         ]
  13.     );
  14.  
  15.  

the source of select box content is 'source' => 'Magento\Eav\Model\Entity\Attribute\Source\Boolean' .

You can get id of custom group id for example 'General Information' :

  1.  
  2. $idg =  $categorySetup->getAttributeGroupId($entityTypeId, $attributeSetId, 'General Information');
  3.  
  4.  

and you can change or add the group of this attribute :

  1.  
  2.     $categorySetup->addAttributeToGroup(
  3.         $entityTypeId,
  4.         $attributeSetId,
  5.         $idg,
  6.         'my_attribute',
  7.         46
  8.     );
  9.  
  10.  

2 – Create custom attribute for customer :

you can download the module CustomerCustomAtttributePut.zip for github  

with the same technique got to InstallData.php and push :

  1.  
  2. <?php
  3. namespace Ibnab\CustomerPut\Setup;
  4.  use Magento\Framework\Module\Setup\Migration;
  5. use Magento\Framework\Setup\InstallDataInterface;
  6. use Magento\Framework\Setup\ModuleContextInterface;
  7. use Magento\Framework\Setup\ModuleDataSetupInterface;
  8. class InstallData implements InstallDataInterface
  9. {
  10.     /**
  11.      * Customer setup factory
  12.      *
  13.      * @var \Magento\Customer\Setup\CustomerSetupFactory
  14.      */
  15.     private $customerSetupFactory;
  16.     /**
  17.      * Init
  18.      *
  19.      * @param \Magento\Customer\Setup\CustomerSetupFactory $customerSetupFactory
  20.      */
  21.     public function __construct(\Magento\Customer\Setup\CustomerSetupFactory $customerSetupFactory)
  22.     {
  23.         $this->customerSetupFactory = $customerSetupFactory;
  24.     }
  25.     /**
  26.      * Installs DB schema for a module
  27.      *
  28.      * @param ModuleDataSetupInterface $setup
  29.      * @param ModuleContextInterface $context
  30.      * @return void
  31.      */
  32.     public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
  33.     {
  34.  
  35.         $installer = $setup;
  36.         $installer->startSetup();
  37.         $customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);
  38.         $entityTypeId = $customerSetup->getEntityTypeId(\Magento\Customer\Model\Customer::ENTITY);
  39.         $customerSetup->removeAttribute(\Magento\Customer\Model\Customer::ENTITY, "my_attribute");
  40.  
  41.         $customerSetup->addAttribute(\Magento\Customer\Model\Customer::ENTITY, "my_attribute",  array(
  42.             "type"     => "varchar",
  43.             "backend"  => "",
  44.             "label"    => "My Attribute",
  45.             "input"    => "text",
  46.             "source"   => "",
  47.             "visible"  => true,
  48.             "required" => true,
  49.             "default" => "",
  50.             "frontend" => "",
  51.             "unique"     => false,
  52.             "note"       => ""
  53.  
  54.         ));
  55.         $my_attribute   = $customerSetup->getAttribute(\Magento\Customer\Model\Customer::ENTITY, "my_attribute");
  56.  
  57.         $my_attribute = $customerSetup->getEavConfig()->getAttribute(\Magento\Customer\Model\Customer::ENTITY, ' my_attribute');
  58.         $used_in_forms[]="adminhtml_customer";
  59.         $used_in_forms[]="checkout_register";
  60.         $used_in_forms[]="customer_account_create";
  61.         $used_in_forms[]="customer_account_edit";
  62.         $used_in_forms[]="adminhtml_checkout";
  63.         $my_attribute->setData("used_in_forms", $used_in_forms)
  64.             ->setData("is_used_for_customer_segment", true)
  65.             ->setData("is_system", 0)
  66.             ->setData("is_user_defined", 1)
  67.             ->setData("is_visible", 1)
  68.             ->setData("sort_order", 100);
  69.         $my_attribute->save();
  70.         $installer->endSetup();
  71.     }
  72. }
  73.  
  74.  

here we added new code we get instance of attribute :

  1.  
  2.  $my_attribute   = $customerSetup->getAttribute(\Magento\Customer\Model\Customer::ENTITY, "my_attribute");
  3.  
  4.  

and we add to custom form as adminhtml_customer,checkout_register" :

  1.  
  2. $my_attribute = $customerSetup->getEavConfig()->getAttribute(\Magento\Customer\Model\Customer::ENTITY, ' my_attribute');
  3.         $used_in_forms[]="adminhtml_customer";
  4.         $used_in_forms[]="checkout_register";
  5.         $used_in_forms[]="customer_account_create";
  6.         $used_in_forms[]="customer_account_edit";
  7.         $used_in_forms[]="adminhtml_checkout";
  8.         $my_attribute->setData("used_in_forms", $used_in_forms)
  9.             ->setData("is_used_for_customer_segment", true)
  10.             ->setData("is_system", 0)
  11.             ->setData("is_user_defined", 1)
  12.             ->setData("is_visible", 1)
  13.             ->setData("sort_order", 100);
  14.  $my_attribute->save();
  15.  
  16.  

 

2 – show custom attribute for customer :

after we added the custom attribute magento 2 show by defaut in in backend for $used_in_forms[]="adminhtml_customer" , but in frontend you need some additional code to  use for example we want show in page customer register ($used_in_forms[]="customer_account_create"):

first inside your module go or create Ibnab/CustomerPut/view/frontend/layout and  create new handler xml customer_account_create.xml and push :

  1.  
  2. <?xml version="1.0"?>
  3. <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
  4.     <body>
  5.         <referenceContainer name="form.additional.info">
  6.             <block class="Magento\Framework\View\Element\Template" name="my_form_additional_info_customer" template="Ibnab_CustomerPut::additionalinfocustomer.phtml"/>
  7.         </referenceContainer>
  8.     </body>
  9. </page>
  10.  
  11.  

Now create .phtml inside Ibnab/CustomerPut/view/frontend/templates  (additionalinfocustomer.phtml) and push :

  1.  
  2.     <fieldset class="fieldset create account" data-hasrequired="<?php /* @escapeNotVerified */ echo __('* Required Fields') ?>">
  3.         <legend class="legend"><span><?php /* @escapeNotVerified */ echo __('Additional Information') ?></span></legend><br></p>
  4.  
  5. <p>        <div class="field my_attribute required">
  6.             <label for="my_attribute" class="label"><span><?php /* @escapeNotVerified */ echo __('My Attribute') ?></span></label>
  7.             <div class="control">
  8.                 <input type="text" name="my_attribute" id="my_attribute" title="<?php /* @escapeNotVerified */ echo __('My Attribute') ?>" class="input-text" data-validate="{required:true}" autocomplete="off">
  9.             </div>
  10.         </div>
  11.         </div>
  12.     </fieldset>
  13.  
  14.  

 

Video workshop :


 

 

ok you can try to create accout your custom field will be showed ....

Comments

Related Posts

make your store more efficient

Solving problems. With open source technology. Professional results. That’s what makes Ibnab your best choice

IBNAB is a company made of a group of professionals whose work is providing secure open source solutions. Our company strives for reaching magnificent results with each experience and provides professional open source solutions that cover every part of the business process.

Newsletter