blog-image
July 25, 2017

Complete Magento 2 Solution to Add Category Attribute Programmatically

Magento

Despite of the high amount of attributes offered in Magento by default, there is always a need to add some new attributes to the system for a particular EAV entity. Here in this article, I will show you how to add a new category attribute programmatically.

In order to do any of the following steps, you need to set up a module. If you are not familiar with how to create a module in Magento 2 follow this article.

First thing required to add an attribute is to create either install or upgrade script inside a Setup folder in the root of your module. If a module is not installed for the first time, install script are required to use.

<?php

namespace InchooAttributeSetup;

use MagentoEavSetupEavSetupFactory;
use MagentoFrameworkSetupModuleContextInterface;
use MagentoFrameworkSetupModuleDataSetupInterface;
use MagentoFrameworkSetupInstallDataInterface;

class InstallData implements InstallDataInterface
{
   private $eavSetupFactory;

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

   public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
   {
       $setup->startSetup(); 

// PLACEHOLDER: add attribute code goes here

       $setup->endSetup();
   }
}

If a module is being upgraded, i.e. we are raising module version, then upgrade script needs to be used. Let’s say we are upgrading our module from version 1.0.0 to version 1.0.1. In that case our upgrade script would look similar to this:

<?php

namespace InchooAttributeSetup;

use MagentoEavSetupEavSetupFactory;
use MagentoFrameworkSetupModuleContextInterface;
use MagentoFrameworkSetupModuleDataSetupInterface;
use MagentoFrameworkSetupUpgradeDataInterface;

class UpgradeData implements UpgradeDataInterface
{
   private $eavSetupFactory;

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

   public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
   {
       $setup->startSetup();

       if ($context->getVersion() && version_compare($context->getVersion(), '1.0.1') < 0) {

           // PLACEHOLDER: add attribute code goes here
       }

       $setup->endSetup();
   }
}

To learn more about install/upgrade scripts read this article by Ivan Weiler.

Part of the install/upgrade script which actually adds a new category attribute looks like this:

$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);

$eavSetup->addAttribute(
   MagentoCatalogModelCategory::ENTITY,
   'inchoo_short_description',
   [
       'type' => 'text',
       'label' => 'Short Description',
       'input' => 'textarea',
       'required' => false,
       'sort_order' => 4,
       'global' => MagentoEavModelEntityAttributeScopedAttributeInterface::SCOPE_STORE,
       'wysiwyg_enabled' => true,
       'is_html_allowed_on_front' => true,
       'group' => 'General Information',
   ]
);

It is necessary to pass the type id of the entity to which we would to add the new attribute (here, it can be said catalog_category) an array of properties for the given attribute. You can place the code mentioned above at the placeholder that is defined in the install/upgrade script. To execute the installed script, only refreshing of the page like Magento 1 can not work. Instead, for Magento 2, to pick up our script, we need to execute the following command:

php bin/magento setup:upgrade

After running it, the new category attribute would be added to the system.Wondering how it can be checked whether it worked or not? Well, it can be checked by going to our database and check setup_module table to see if the versions of the module matchup:

And/or we can check eav_attribute table for an attribute with the attribute code defined in our install/upgrade script. You should see something like this:

If you are not satisfied by that, you can go to the Magento admin, open the category and the newly added attribute would be seen there. If you are unable to see, you are working with Magento 2.1 or above. Earlier, versions before 2.1 were run on old forms/tabs interface which automatically pick your newly added attribute. All fields and field sets are defined in the XML file for the UI component which is located here:

MagentoCatalogviewadminhtmlui_componentcategory_form.xml

In order to add the new attribute to the category edit form we need to create xml file in our module on the same path with the same name. So in your module, inside

Vendor_Name/Module_Name/view/adminhtml/ui_component folder create a file called category_form.xml

and populate it with the xml similar to this:

<?xml version="1.0" encoding="UTF-8"?>
<form  xsi_noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
   <fieldset name="content">
        <field name="inchoo_short_description">
           <argument name="data" xsi_type="array">
               <item name="config" xsi_type="array">
                   <item name="class" xsi_type="string">MagentoCatalogUiComponentCategoryFormElementWysiwyg</item>
                   <item name="formElement" xsi_type="string">wysiwyg</item>
           <item name="label" xsi_type="string" translate="true">Short Description</item>
                   <item name="wysiwygConfigData" xsi_type="array">
                       <item name="settings" xsi_type="array">
                           <item name="theme_advanced_buttons1" xsi_type="string">bold,italic,|,justifyleft,justifycenter,justifyright,|,fontselect,fontsizeselect,|,forecolor,backcolor,|,link,unlink,image,|,bullist,numlist,|,code</item>
                           <item name="theme_advanced_buttons2" xsi_type="boolean">false</item>
                           <item name="theme_advanced_buttons3" xsi_type="boolean">false</item>
                           <item name="theme_advanced_buttons4" xsi_type="boolean">false</item>
                           <item name="theme_advanced_statusbar_location" xsi_type="boolean">false</item>
                       </item>
                       <item name="files_browser_window_url" xsi_type="boolean">false</item>
                       <item name="height" xsi_type="string">100px</item>
                       <item name="toggle_button" xsi_type="boolean">false</item>
                       <item name="add_variables" xsi_type="boolean">false</item>
                       <item name="add_widgets" xsi_type="boolean">false</item>
                       <item name="add_images" xsi_type="boolean">false</item>
                   </item>
                   <item name="template" xsi_type="string">ui/form/field</item>
                   <item name="source" xsi_type="string">category</item>
                   <item name="wysiwyg" xsi_type="boolean">true</item>
                   <item name="dataScope" xsi_type="string">inchoo_short_description</item>
                   <item name="sortOrder" xsi_type="number">50</item>
                   <item name="rows" xsi_type="number">8</item>
               </item>
           </argument>
       </field>
   </fieldset>
</form>

Related : Top Extensions That Must Be Used in Magento Ecommerce Store

For your custom field, structure of xml depends on the type of attribute added by you. By adding the above description attribute, one can reuse the xml of the default category description attribute and change the certain things. Most importantly, it is necessary to change the field name which has to match the code of the attribute, you are adding to the form. In this case, it is inchoo_short_description. Files to look for are mostly located in

/view/adminhtml/ui_component/ folder of the modules.

Once this is done, you would be able to find your custom attribute in the category edit page. Be aware, Clear the cache without fail, if they are enabled.

So, this is how to add a new category attribute to your Magento 2 programmatically. The procedure for adding the attribute to some other EAV_attribute remains the same. Just replace the entity type id of the entity in which you would like to add the new attribute and adjust the attribute properties according to the requirement.

Read this article : Is Gamification Effective For Ecommerce Stores? Know From Experts

Read More

Popular posts like this

Consultation

Free

Get a definite increase in the sales enquiries on your eCommerce store by contacting our highly approachable sales team today!

No Credit Card Required, No Commitment, No Cash.
Call Today +61 413 223 826
24x7 Support [email protected]