1

I'm currently building a multi-list of product filter options which will have lists of current attribute values, and sit in the main navigation menu, such as this:

Color       Animal     Foo
---------   --------   ---------
Red         Cat        Foo
Blue        Dog        Bar
Green       Snake      Foobar

However, whenever I call getUrl() on the filter item, it adds the filter item option with the options already in the URL. E.g.,

Current URL: example.com/cat/red.html

And if I then want to click on Bar, it will give me: example.com/cat/red-bar.html instead of just example.com/bar.html.

My current code is below; help, what am I doing wrong/need to do!?

class ExampleWidget extends Template implements BlockInterface
{
    protected $_template = "widget/examplewidget.phtml";

    public function __construct(
        Template\Context $context,
        \Magento\Framework\ObjectManagerInterface $objectManager,
        \Magento\Catalog\Model\CategoryFactory $categoryFactory,
        \Magento\Catalog\Model\Layer\Category\FilterableAttributeList $filterableAttributeList,
        \Magento\Catalog\Model\Layer\Resolver $resolver
    ) {
        $this->_categoryFactory = $categoryFactory;
        $this->_filterableAttributeList = $filterableAttributeList;
        $this->_resolver = $resolver;
        $this->_objectManager = $objectManager;
        parent::__construct($context);
    }

    public function getCategoryAttributeOptions($categoryId, $attrinuteName)
    {
        // Get the attributes that are filterable
        $filterList = $this->_objectManager->getInstance()->create(
            \Magento\Catalog\Model\Layer\FilterList::class, [
                'filterableAttributes' => $this->_filterableAttributeList
            ]
        );

        // Filter to just this category
        $layer = $this->_resolver->get();
        $layer->setCurrentCategory($categoryId);
        $filters = $filterList->getFilters($layer);

        $options = [];
        foreach ($filters as $filter) {
            // We don't want this attribute
            if ($filter->getName() != $attrinuteName) {
                continue;
            }

            // Don't show options with no items
            if (! $filter->getItemsCount()) {
                continue;
            }

            foreach ($filter->getItems() as $item) {
                $options[] = [
                    "label" => $item->getLabel(),
                    "url" => $item->getUrl()
                ];
            }
        }

        return $options;
    }

Your Answer

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

Browse other questions tagged or ask your own question.