Elsner INC Delivers Splendid

Complete Magento 2 Solution to Add Category Attribute Programmatically

blog-img

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 Inchoo\Attribute\Setup;

use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\InstallDataInterface;

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 Inchoo\Attribute\Setup;

use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\UpgradeDataInterface;

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(
   \Magento\Catalog\Model\Category::ENTITY,
   'inchoo_short_description',
   [
       'type' => 'text',
       'label' => 'Short Description',
       'input' => 'textarea',
       'required' => false,
       'sort_order' => 4,
       'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::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:

Magento\Catalog\view\adminhtml\ui_component\category_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 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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">Magento\Catalog\Ui\Component\Category\Form\Element\Wysiwyg</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

 

July 2017

Dipak Patil

Related Posts

Hello @ Elsner Technology Pvt. Ltd.

Elsner Technology introduces their enthusiastic and responsive developers who promise to give high caliber and financially productive Web development, Design & Digital marketing solutions for customers over the globe. Very much updated with all the most recent innovations and market movements, our group of devoted developers are prepared thoroughly to convey bespoke, practical and superior solution for your business.

Get Free Quote

Recent Posts

Write for us

Contribute to out blog

Tags Cloud