magento 2 create product attribute programmatically

Magento 2 Create Product Attribute Programmatically

by TuanVN

Magento 2 create product attribute programmatically can be very helpful if you know the right way to do it.

Recently, we received some questions on Magento 2 custom product attributes and options – how to add them programmatically instead of the dull manual task as the default. Without a tiny doubt, enriching products with more and more diverse options becomes the daily work of online merchants. As a developer, if you know how to speed it up the right way, then be ready to get proper payment!

Do not want to beat around the bush anymore; you are ready to get straight to our topic today: “How to Add Product Attributes and Options Programmatically in Magento 2”. Then, let’s begin.

Magento 2 Create Product Attribute Programmatically

Step 1: Create a new module named Bss_AddProductAttribute

The first step to creating module Magento 2 is to add the below code in the app/code/Bss/AddProductAttribute/registration.php:

<?php

\Magento\Framework\Component\ComponentRegistrar::register(

    \Magento\Framework\Component\ComponentRegistrar::MODULE,

Bss_AddProductAttribute’,

__DIR__

);

In the app/code/Bss/AddProductAttribute/composer.json create as below:

{

"name": "bss/addproductattribute",

"description": "Bss Add Product Attribute",

"require": {

   "php": "~5.6.0|7.0.2|~7.0.6"

},

"type": "magento2-module",

"version": "1.0.0",

"license": [

     "OSL-3.0",

    "AFL-3.0"

],

"extra": {

     "map": [

         [

             "*",
             "Bss/AddProductAttribute"

         ]

     ]

}

}

And, add the following code in the app/code/Bss/AddProductAttribute/etc/module.xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"

>

<module name="Bss_AddProductAttribute" setup_version="1.0.0" />

 </config>

Step 2: Create the file InstallData.php

<?php

namespace Bss\AddProductAttribute\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\Catalog\Model\Product::ENTITY,

           'custom_attribute',

           [

               'group' => 'General’,

   'attribute_set_id' => 'Bag',

               'type' => ’varchar,

               'backend' => '',

               'frontend' => '’',

               'label' => 'Custom Attribute',

               'input' => ‘text’,

               'class' => '',

               'source' => '’',

               'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL,

               'visible' => true,

               'required' => false,

               'user_defined' => true,

               'default' => 0,

               'searchable' => true,

               'filterable' => true,

               'comparable' => true,

               'visible_on_front' => true,

               'sort_order' => 101,

           'option' => [

       'values' => [],

   ]

]

 

           ]

       );

   }

}

You must get to know the following setup for creating new attributes:

  • group: Name of groups that you want the created attribute to display in, such as General, Bundle, Items, Images, Content, etc. Set Group to General to assign the attribute to all groups.
  • attribute_set_id: Define the attribute set to which the attribute is added, for example, Bag, Default, Gear, Bottom, etc.
  • type: Select the type of custom value saved in the database.
  • input: Specify the input type of the attributes such as select, text, and boolean.
  • label: Set the label of the attribute displayed both in the frontend and in the backend.
  • source model: there is a list of options.
  • frontend: Define how to show the attribute in the frontend.
  • backend: the admin can take some specific actions when loading or saving the attribute.
  • global: select the scope of the attribute among global, website, or store.
  • require: decide whether the attribute is required or optional.
  • visible_on_store: decide whether the attribute is displayed in “More Information” tab of the frontend.
  • sort order: define the order of attributes.

Step 3: Run php bin/magento setup:upgrade

Please follow Admin panel ⇒ Stores ⇒ Product to find the custom attribute already added.

On Product Edit Page, you can see the attribute to be displayed.

Step 4: Create Attributes with Options

Above, we learn to create Magento 2 custom product attribute programmatically without options. Hence, you can skip the following steps if you only want to create attributes with input types such as text or text area.

In case you want to create product attributes with options programmatically, in step 2, please modify some codes, as below:

‘source’ => ‘’  into :

‘source’ => Bss\AddProductAttribute\Model\Attribute\Source\CustomAttribute

Step 5: Add source model

In the app/code/Bss/AddProductAttribute/Model/Attribute/Source/CustomAttribute.php please add the code:

<?php

namespace Bss\AddProductAttribute\Model\Attribute\Backend;

 

class CustomAttribute extends \Magento\Eav\Model\Entity\Attribute\Source\AbstractSource

{

  /**

   * Get all options

   * @return array

   */

  public function getAllOptions()

  {

      if (!$this->_options) {

          $this->_options = [

              ['label' => __('One'), 'value' => 'one'],

              ['label' => __('Two'), 'value' => 'two'],

              ['label' => __('Three'), 'value' => 'three'],

              ['label' => __('Four'), 'value' => 'four'],

              ['label' => __('Five'), 'value' => 'five'],

              ['label' => __('Six'), 'value' => 'six'],

          ];

      }

      return $this->_options;

  }

/**

* Get a text for option value

*

* @param string|integer $value

* @return string|bool

*/

public function getOptionText($value)

{

  foreach ($this->getAllOptions() as $option) {

      if ($option['value'] == $value) {

          return $option['label'];

      }

  }

  return false;

}

}

Then, run php bin/magento setup:upgrade và setup:static-content:deploy -f .

Here we get the result:

>>>If using code feels too complex, we’ve got you covered! Check out our easy-to-follow manual guide for adding new product attributes through the Magento 2 backend: How to Add New Magento 2 Product Attributes. Perfect for non-developers looking for a simpler solution! 

Conclusion

This is all about Magento 2 create product attribute programmatically. We complete the guide through how to add product attributes and options programmatically in Magento 2. If you have any questions, feel free to leave them below. We are willing to help you out as soon as possible.

BSS Commerce is one of the leading Magento extension providers and web development services in the world. With experienced and certified Magento developers, we commit to bringing high-quality products and services to optimize your business effectively. Furthermore, we offer FREE Installation – FREE 1-year Support and FREE Lifetime Update for every Magento extension.

CONTACT NOW to let us know your problems. We are willing to support you every time.

Next Reading Suggestions

© 2019 BSS Commerce owned by THANH CONG INTER ., JSC. All Rights Reserved.
Business registration certificate no. 0106064469 issued by Hanoi Department of Planning and Investment on 19 December 2019.
Legal Representative: Mr. Nguyen Quang Trung.