Oh snap! You are using an old version of browser. Update your browser to get new awesome features. Click for more details.

Magento 2 - Get product active filters using Event Obeserver


Create events.xml

Path: app/code/Module_Name_Space/Module_Name/etc/frontend/events.xml

Put this code

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="layout_generate_blocks_after">
    <observer name="customize-category-block" instance="Module_Name_Space/Module_Name\Observer\Filters" />
</event>
</config>


Now create observer file Filters.php

Path: app/code/Indianic/CategoryTab/Observer/Filters.php

Put this code

<?php
namespace Module_Name_Space\Module_Name\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Catalog\Model\Layer\Resolver as LayerResolver;

class Categoryblock implements ObserverInterface
{
    /**
     * @var \Magento\Catalog\Model\Layer\Category
     */
    protected $catalogLayer;

    public function __construct(
        LayerResolver $layerResolver
    ) {
        $this->catalogLayer = $layerResolver->get();
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
{
    $action = $observer->getData('full_action_name');
    if ($action !== 'catalog_category_view') {
        return;
    }

        // Get selected filters
        $layer = $this->catalogLayer;
        $activeFilters = $layer->getState()->getFilters();
}
}

Also you can unset layout this observer, put below code in execute function

/** @var \Magento\Framework\View\Layout $layout */
$layout = $observer->getData('layout');
$layout->unsetElement('Element_Name_Here');

(0) comments