Magento2 | PWA | GraphQL

How to add extra category description (textarea category EAV attribute) in the product listing page - Magento2


In this tutorial, you will learn How to add extra category description on product list page by adding textarea as a category EAV attribute.

Let's start it by creating custom module.

Find Complete Module on Github

Create folder in app/code/Magelearn/CustomInfo

Step 1: Create module registration file

Add registration.php file in it:
<?php
/**
 * Copyright ©  All rights reserved.
 * See COPYING.txt for license details.
 */
use Magento\Framework\Component\ComponentRegistrar;

ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Magelearn_CustomInfo', __DIR__);
Add composer.json file in it:
{
    "name": "magelearn/module-CustomInfo",
    "description": "Magento2 add extra category description on product list page by adding textarea as a category EAV attribute",
    "type": "magento2-module",
    "license": "OSL-3.0",
    "authors": [
        {
            "email": "info@mage2gen.com",
            "name": "Mage2Gen"
        },
        {
            "email": "vijaymrami@gmail.com",
            "name": "vijay rami"
        }
    ],
    "minimum-stability": "dev",
    "require": {},
    "autoload": {
        "files": [
            "registration.php"
        ],
        "psr-4": {
            "Magelearn\\CustomInfo\\": ""
        }
    }
}
Add etc/module.xml file in it:
<?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="Magelearn_CustomInfo" setup_version="1.0.0">
</module> </config>

Step 2. Create the Bottom Description field in the backend.

Create InstallData.php inside Magelearn/CustomInfo/Setup
<?php
namespace Magelearn\CustomInfo\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;
use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface;

/**
 * @codeCoverageIgnore
 */
class InstallData implements InstallDataInterface
{
    /**
     * EAV setup factory.
     *
     * @var EavSetupFactory
     */
    private $_eavSetupFactory;
    protected $categorySetupFactory;

    /**
     * Init.
     *
     * @param EavSetupFactory $eavSetupFactory
     */
    public function __construct(EavSetupFactory $eavSetupFactory, \Magento\Catalog\Setup\CategorySetupFactory $categorySetupFactory)
    {
        $this->_eavSetupFactory = $eavSetupFactory;
        $this->categorySetupFactory = $categorySetupFactory;
    }

    /**
     * {@inheritdoc}
     *
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    public function install(
        ModuleDataSetupInterface $setup,
        ModuleContextInterface $context
    ) {
        /** @var EavSetup $eavSetup */
        $eavSetup = $this->_eavSetupFactory->create(['setup' => $setup]);
        $setup = $this->categorySetupFactory->create(['setup' => $setup]);         
        $setup->addAttribute(
            \Magento\Catalog\Model\Category::ENTITY, 'bottom_description', [
'type' => 'text', 'label' => 'Bottom Description', 'input' => 'textarea', 'required' => false, 'sort_order' => 9, 'wysiwyg_enabled' => true, 'is_html_allowed_on_front' => true, 'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_STORE, 'group' => 'General Information' ] ); } }
This code snippet below will add a visual Bottom Description attribute for the categories in the admin panel, which includes WYSIWYG editor enabled.

Create category_form.xml inside Magelearn/CustomInfo/view/adminhtml/ui_component
<?xml version="1.0" ?>
<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="bottom_description" template="ui/form/field" sortOrder="60" formElement="wysiwyg">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="wysiwygConfigData" xsi:type="array">
                        <item name="height" xsi:type="string">100px</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">true</item>
                        <item name="add_directives" xsi:type="boolean">true</item>
                    </item>
                    <item name="source" xsi:type="string">category</item>
                </item>
            </argument>
            <settings>
                <label translate="true">Bottom Description</label>
                <dataScope>bottom_description</dataScope>
            </settings>
            <formElements>
                <wysiwyg class="Magento\Catalog\Ui\Component\Category\Form\Element\Wysiwyg">
                    <settings>
                        <rows>8</rows>
                        <wysiwyg>true</wysiwyg>
                    </settings>
                </wysiwyg>
            </formElements>
        </field>
    </fieldset>
</form>
After adding those files above you should see the field below category description.


Step 3. Make visible in the product listing page.

Here, we will push the texts we added in the backend. First, you need to create a phtml file which contains the attribute text. Then you can put the text to bottom in the category page.

Create catalog_category_view.xml inside Magelearn/CustomInfo/view/frontend/layout
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="2columns-left" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block class="Magelearn\CustomInfo\Block\Info" name="bottom.description" template="Magelearn_CustomInfo::product/list/bottom_description.phtml" before="-"/>
        </referenceContainer>
    </body>
</page>
Here we add our custom block and before="-" will add this bottom description content before the category content. 

Create Info.php inside Magelearn/CustomInfo/Block
<?php
/**
 * Copyright © 2013-2017 Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * Product description block
 *
 * @author     Magento Core Team <core@magentocommerce.com>
 */
namespace Magelearn\CustomInfo\Block;

class Info extends \Magento\Framework\View\Element\Template
{
    /**
     * @var Product
     */
    protected $_category = null;

    /**
     * Core registry
     *
     * @var \Magento\Framework\Registry
     */
    protected $_coreRegistry = null;

    /**
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param \Magento\Framework\Registry $registry
     * @param array $data
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Framework\Registry $registry,
        array $data = []
    )
    {
        $this->_coreRegistry = $registry;
        parent::__construct($context, $data);
    }
    /**
     * Retrieve current category model object
     *
     * @return \Magento\Catalog\Model\Category
     */
    public function getCurrentCategory()
    {
        if (!$this->_category) {
            $this->_category = $this->_coreRegistry->registry('current_category');

            if (!$this->_category) {
                throw new \Magento\Framework\Exception\LocalizedException(__('Category object could not be found in core registry'));
            }
        }
        return $this->_category;
    }
}
At last, Create bottom_description.phtml inside Magelearn/CustomInfo/view/frontend/templates/product/list
<?php
$current_category = $block->getCurrentCategory();
if ($_bottomDescription = $current_category->getBottomDescription()): ?>
    <div class="category-bottom-description">
        <?= /* @escapeNotVerified */ $this->helper('Magento\Catalog\Helper\Output')->categoryAttribute($block->getCurrentCategory(), $_bottomDescription, 'bottom_description') ?>
    </div>
<?php endif; ?>
After doing all the steps above. Enable the module, generate classes and refresh the cache. If everything was well, now you should see something like this.




0 Comments On "How to add extra category description (textarea category EAV attribute) in the product listing page - Magento2"

Back To Top