0

I cannot find it di.xml. Any ideas?

I want to add a custom css class to specific TopMenu items. I don't know how to extend this.

2
  • Since it is a 'protected' method, you need to use a rewrite/preference. Commented May 25, 2022 at 20:00
  • I did, but the menu isn't rendering. Commented May 25, 2022 at 21:23

1 Answer 1

1

For overriding the topmenu class you can preference.

step1

Add di.xml in Shahroz/Menu/etc/di.xml

<?xml version="1.0" ?>
<config>
    <preference for="Magento\Theme\Block\Html\Topmenu" type="Shahroz\Menu\Block\Html\Topmenu" />
</config>

step2

create custom class Shahroz\Menu\Block\Html\Topmenu.php

<?php

namespace Shahroz\Menu\Block\Html;

use Magento\Framework\Data\Tree\Node;
use Magento\Theme\Block\Html\Topmenu as MagentoTopmenu;

class Topmenu extends  MagentoTopmenu
{

    /**
     * Returns array of menu item's classes
     *
     * @param Node $item
     * @return array
     */
    protected function _getMenuItemClasses(Node $item)
    {
        $writer = new \Zend_Log_Writer_Stream(BP . '/var/log/topmenu.log');
        $logger = new \Zend_Log();
        $logger->addWriter($writer);
        $logger->info('text message');
        $classes = [
            'level' . $item->getLevel(),
            $item->getPositionClass(),
        ];

        if ($item->getIsCategory()) {
            $classes[] = 'category-item';
        }

        if ($item->getIsFirst()) {
            $classes[] = 'first';
        }

        if ($item->getIsActive()) {
            $classes[] = 'active';
        } elseif ($item->getHasActive()) {
            $classes[] = 'has-active';
        }

        if ($item->getIsLast()) {
            $classes[] = 'last';
        }

        if ($item->getClass()) {
            $classes[] = $item->getClass();
        }

        if ($item->hasChildren()) {
            $classes[] = 'parent';
        }

        return $classes;
    }
}

Step3

Now you can check var/log there will be new log file topmenu.log.If the file is there its means your are successful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.