How to create product attribute in Magento 2

By hammad.usmani, 10 November, 2016

It might be simple to add a custom attribute for a product simply by using admin panel, but most of the extensions provide documentation on how to do that. If you are creating that attribute by using the installers so with your extension installation a new attribute will be created using installer. We can use installer for any action that we want to perform with the installation of our extension. e.g.: adding an attribute in product or category or any extension or changes in customers etc. It easier to develop the extension in the earlier version e.g. Magento 1, but for Magento 2.x its not that simple. The main difference is only in the extension’s structure as Magento 2 has more ‘developer-friendly’ architecture and allows the developers to interact in many ways to avoid conflicts. We had code pools prior Magento 2 e.g. community, core and local but in Magento 2 we don’t need to worry about the code pools. We directly put the extension in the code folder. So our code for the extension will be in this directory:

app/code/[VendorName]/[ExtensionName]

Let’s assume here the vendor name is “Aalogics” and Extension what we are going to develop is named as “NewAttribute”, so it will look like this:

app/code/Aalogics/NewAttribute

Now define your new module by creating a module.xml in the etc folder: e.g.

app/code/Aalogics/NewAttribute/etc/

The module.xml structure looks like this:

<?xmlversion="1.0"?> <configxmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> <modulename="Aalogics_NewAttribute"setup_version="1.0.0"> </module> </config>

Here is a difference in XML file like in Magento 2 we have schema definitions that allow to validate the XML in different places.

Now after defining the “module.xml” we have to create a “registration.php” file and place it in the extension’s root directory:

The code for the “registration.php” will look like this:

\Magento\Framework\Component\ComponentRegistrar::register( \Magento\Framework\Component\ComponentRegistrar::MODULE, 'Aalogics_ NewAttribute’, __DIR__ );

After registering the extension now it’s time to write the installer for our extension:

First Let’s take a look at Magento 2’s the six different Setup classes in your module:

InstallSchema

this class will run while the module is installed to setup database structure

InstallData

this class will run when the module is installed.

UpgradeSchema

this class will run when the module is upgraded to setup the database structure

UpgradeData

this class will run when the there is any change in module and it is upgraded to add/remove data from table or any other upgrade action.

Recurring

Uninstall

All of these 6 classes will be located at app/code/Vendor/Module/Setup/ folder.

Let’s create a folder named Setup in extensions’ root directory and a file “InstallData.php” in it:

The code for the “InstallData.php” will look like this to add a new attribute in product:

<?php /* app/code/Aalogics/NewAttribute/Setup/InstallData.php */ namespaceAalogics\NewAttribute\Setup; useMagento\Eav\Setup\EavSetup; useMagento\Eav\Setup\EavSetupFactory; useMagento\Framework\Setup\InstallDataInterface; useMagento\Framework\Setup\ModuleContextInterface; useMagento\Framework\Setup\ModuleDataSetupInterface; /** * @codeCoverageIgnore */ classInstallData implementsInstallDataInterface { /** * EAV setup factory * * @var EavSetupFactory */ private$eavSetupFactory; /** * Init * * @param EavSetupFactory $eavSetupFactory */ publicfunction__construct(EavSetupFactory $eavSetupFactory) { $this->eavSetupFactory = $eavSetupFactory; } /** * {@inheritdoc} * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ publicfunctioninstall(ModuleDataSetupInterface $setup, ModuleContextInterface $context) { /** @var EavSetup $eavSetup */ $eavSetup= $this->eavSetupFactory->create(['setup'=> $setup]); /** * Add attributes to the eav/attribute */ $eavSetup->addAttribute( \Magento\Catalog\Model\Product::ENTITY, 'YOUR_ATTRIBUTE_NAME, [ 'type'=> 'varchar', 'backend'=> '', 'frontend'=> '', 'label'=> LABEL FOR YOUR ATTRIBUTE', 'input'=> 'text', 'class'=> '', 'source'=> '', 'global'=> \Magento\Catalog\Model\Resource\Eav\Attribute::SCOPE_GLOBAL, 'visible'=> true, 'required'=> false, 'user_defined'=> false, 'default'=> 0, 'searchable'=> false, 'filterable'=> false, 'comparable'=> false, 'visible_on_front'=> false, 'used_in_product_listing'=> true, 'unique'=> false, 'apply_to'=> '' ] ); } }

Yes we are done with the code and it will create a new product attribute in the system. Now it is the time to enable our extension and let the Magento know that we have some files changed that needs to be executed.

Go to your CLI in [MagentoRoot]/bin directory and run this command:

php magento module:enable Aalogics_NewAttribute

Now the next step is to clean the cache:

The easiest way is to remove [MagentoRoot]/var/cache/ and [MagentoRoot]/var/page_cache/ directories.

After clearing cache go to [MagentoRoot]/bin in CLI and run command to check if everything goes fine:

php magento setup:db:status

You will see the output like: 
The module code base doesn't match the DB schema and data. Aalogics_NewAttribute schema:none -> 1.0.0 Aalogics_NewAttribute data:none -> 1.0.0 Run 'setup:upgrade'to update your DB schema and data.

So now run the “setup:upgrade” command:

php magento setup:upgrade

Hurrah! You have done it. Now you can see a new field in products attributes if you have done everything correctly. Feel free to ask questions if you are facing any trouble. Thank you!

AAlogics (Pvt) Ltd is a Magento development company. We extensively work on custom Magento themes and Extension. Hire Magento Developers from AALogics if you have any query related to Magento and its product.