0

I just want add a custom function in layered navigation block Magento\LayeredNavigation\Block\Navigation

the function :

public function getActiveFilters()
{
   $filters = $this->getLayer()->getState()->getFilters();
   if (!is_array($filters)) {
        $filters = [];
   }
   return $filters;
}

ive tried to create custom module to override block with preferences as well as plugin, but no luck its not working.

at first try, im using preference. I use this code in

Vendor\Module\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\LayeredNavigation\Block\Navigation" type="Vendor\Module\Block\Navigation" />
</config>

and create block in my custom module

<?php
namespace Vendor\Module\Block;

class Navigation extends \Magento\LayeredNavigation\Block\Navigation
{
    /**
     * Retrieve active filters
     *
     * @return array
     */
    public function getActiveFilters()
    {
        $filters = $this->getLayer()->getState()->getFilters();
        if (!is_array($filters)) {
            $filters = [];
        }
        return $filters;
    }
}

but its not working, as well as using plugin to override block.

am I missing something? and what is the best way to override block?

Thanks in Advance.

0

This is because \Magento\LayeredNavigation\Block\Navigation::getActiveFilters does't exist.

The method in your question appears to be from \Magento\LayeredNavigation\Block\Navigation\State::getActiveFilters so you would need to update your di.xml to reflect this. It is also recommended to use interceptors (plugins) over rewrites

Vendor\Module\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">
    <type name="Magento\LayeredNavigation\Block\Navigation\State">
        <plugin name="Vendor_Module::filterActiveLayeredNavigationItems" type="Vendor\Module\Plugin\Block\LayeredNavigation\Navigation\State"/>
    </type>
</config>

app/code/Vendor/Module/Plugin/Block/LayeredNavigation/Navigation/State.php

<?php

namespace Vendor\Module\Plugin\Block\LayeredNavigation\Navigation;

class State
{
    /**
     * @param \Magento\LayeredNavigation\Block\Navigation\State $subject
     * @param array                                             $result
     *
     * @return array
     */
    public function afterGetActiveFilters(
        \Magento\LayeredNavigation\Block\Navigation\State $subject,
        $result = []
    ) {
        $result = $this->doYourLogic($result);

        return $result;
    }
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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