Magento – Magento 2 (2.0.7) How to edit a a .php file from module-theme for your own theme

magento-2.0.7magento2

I want to adjust the header menu. It works a bit by editing topmenu.phtml, at least for the $outermostClass to add some classes but I think $childrenWrapClass has an error since in function _addSubMenu in topmenu.php it does not use the var.

Though anyway, I would need more than adding a class to submenus. I would need to make the links look like

<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">

So I would need to edit topmenu.php in any way.

How to edit the topmenu.php? It is located originally in module-theme/Block/Html/Topmenu.php

Can I place it in my theme directory somewhere simply?

Someone mentioned I would need to create a module for it. Does that mean creating a directory on the same level of Magento_Theme in my theme directory? If so then how to name that directory and where to place my topmenu.php in order to use this instead the original one?

Thank you!

Best Answer

You have to create module for changes in Topmenu.php file,

File path is : app/code

Create module name Package/Topmenu/registration.php,

<?php

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Package_Topmenu',
    __DIR__
);

Package/Topmenu/etc/module.xml,

<?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="Package_Topmenu" setup_version="1.0.0"></module>
</config>

Create di.xml file for override topmenu file,

filepath is Package/Topmenu/etc/di.xml,

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magento\Theme\Block\Html\Topmenu" type="Package\Topmenu\Block\Topmenu"/>
</config>

Create block for override topmenu file function, Package/Topmenu/Block/Topmenu.php,

<?php

namespace Package\Topmenu\Block;

class Topmenu extends \Magento\Theme\Block\Html\Topmenu
{
     //override core function here..

}

Run command , php bin/magento setup:upgrade

Clear cache and check now its overrider core block.

Related Topic