Magento2 – How to Show EAV Custom Attribute of Category in PHTML File

magento2

I have created a custom EAV attribute called "Force Grid Mod" using the script below. Now I don't know how to show its value in list.phtml. Its working on the backend. Does someone knows how can I show its value in my list.phtml ?

<?php


namespace VendorName\ModuleName\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\Category::ENTITY,
            'force_grid_mode',
            [
                        'type' => 'int',
                        'label' => 'Force Grid mod',
                        'input' => 'select',
                        'source' => 'Magento\Eav\Model\Entity\Attribute\Source\Boolean',
                        'required' => false,
                        'sort_order' => 30,
                        'group' => 'Display Settings',
            ]
        );
    }
}

Best Answer

Do you mean /module-catalog/view/frontend/templates/product/list.phtml? If yes then you can access current category through layer object:

$_layer = $this->getLayer();
$_category = $_layer->getCurrentCategory();

And on this category object you can call your new attribute:

$_category->getForceGridMode()
Related Topic