How to Add an Attribute in Magento 2?

  • author-img Nidhi Arora
  • 6 years
  • 212 views

While developing a Magento extension, if there is a need to add an attribute programmatically in Magento 2, it is really easy as compared to Magento 1.x. Since Magento 2 features a more developer-friendly’ architecture and offers much more convenient methods to interact with the core & keep away from different kinds of conflicts. Magento 2 has no code pools, so there is no chance of any dispute regarding the right place where to put the code. Following is the right path to put the main files of extension:

app/code/[VendorName]/[ExtensionName]

Crate an extension in this directory based on the above:

app/code/Eecom/CustomAttribute/

A file named as module.xml in the app/code/ Eecom/CustomAttribute directory is required to define our new module by the means of following content:

<?xml version="1.0"?>

<config xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">

<module name=" Eecom _ CustomAttribute " setup_version="1.0.0">

<sequence>

<module name="Magento_Catalog"/>

</sequence>

</module>

</config>

As you can observe that XML files in Magento 2 features schema definitions that permit to validate your XML in different positions. The <sequence> node is used to express your extension’s dependencies, same like <depends> node is used in Magento 1.x. Now, it is our next step where we require developing the data script through the parameters of the new attribute:

<?php

/* app/code/Eecom/CustomAttribute/Setup/InstallData.php */

namespace Eecom\CustomAttribute\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;

/**

* @codeCoverageIgnore

*/

class InstallData implements InstallDataInterface

{

/**

* EAV setup factory

*

* @var EavSetupFactory

*/

private $eavSetupFactory;

/**

* Init

*

* @param EavSetupFactory $eavSetupFactory

*/

public function __construct(EavSetupFactory $eavSetupFactory)

{

$this->eavSetupFactory = $eavSetupFactory;

}

/**

* {@inheritdoc}

* @SuppressWarnings(PHPMD.ExcessiveMethodLength)

*/

public function install(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,

'requestforprice_text',

[

'group' => 'General',

'type' => 'varchar',

'backend' => '',

'frontend' => '',

'label' => 'Request for Price Label',

'input' => 'textarea',

'class' => '',

'source' => '',

'global' => \Magento\Catalog\Model\ResourceModel\Eav\Attribute::SCOPE_GLOBAL,

'visible' => true,

'required' => false,

'user_defined' => true,

'default' => '',

'searchable' => false,

'filterable' => false,

'comparable' => false,

'visible_on_front' => false,

'used_in_product_listing' => true,

'unique' => false,

'apply_to' => 'simple,configurable,virtual,bundle,downloadable'

]

After expressing all parameters of the new attribute, we have the need to tell Magento about the files with the installation instructions that require to be executed. To enable the extension along with your Magento 2  0.74.0-beta4 or later, you can apply a CLI command. Go to [magento_root]/bin directory and apply the command as mentioned below:

php magento module:enable Eecom_CustomAttribute

Now, it is required to clean the cache (How to Clean & Manage Cache in Magento 2 – please check our previous post) and verify that everything is working fine. Go to [magento_root]/bin directory and apply the command as mentioned below:

php magento setup:db:status

Now, we require synchronizing the database with a setup version of the module. Run the following command to execute data setup script & synchronize the process for adding an attribute:

php magento setup:upgrade

After running all the aforementioned commands, you should now able to have the new attribute in Magento 2. Hope we have clearly explained all coding & commands. If you have any query, feel free to contact us and share your own findings or suggestions as well.

Download Blog

ENQUIRY

Ready to Get started

Communication is the key for us to understand each other. Allow us to understand
your requirements or queries. Present us with an opportunity to serve you.

Fill out the form and out team will get back to you
within 24 hours

    Head Office

    1250 Pittsford Victor Road Ste 310
    Pittsford, NY 14534

    Development Center

    Plot no. 10, Rajiv Gandhi
    Chandigarh Technology Park