0

How can we fetch all the available filter attributes in the category page with REST API?

I'm working with the mobile app for my Magento store. In the category listing page, I need to show all the available filters for the category and with this filter, I need to show the products accordingly.

  • Available filter list for the category page.
  • Filtering the product in the category page based on the selected filter.

Also, I just want to know how this can be implemented within the search page.

Any help would be appreciable.

1
2

Please try the following code

public function getCategoryFilter($id)
{
    $resultJson = $this->_resultJsonFactory->create();

    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();

    $filterableAttributes = $objectManager->getInstance()->get(\Magento\Catalog\Model\Layer\Category\FilterableAttributeList::class);

    $appState = $objectManager->getInstance()->get(\Magento\Framework\App\State::class);
    $layerResolver = $objectManager->getInstance()->get(\Magento\Catalog\Model\Layer\Resolver::class);
    $filterList = $objectManager->getInstance()->create(
        \Magento\Catalog\Model\Layer\FilterList::class,
        [
            'filterableAttributes' => $filterableAttributes
        ]
    );

    $layer = $layerResolver->get();
    if($id != 0)
    {
        $layer->setCurrentCategory($id);
    }        
    $filters = $filterList->getFilters($layer);
    $maxPrice = $layer->getProductCollection()->getMaxPrice();
    $minPrice = $layer->getProductCollection()->getMinPrice();


    $i = 0;
    $finalFilters = [];
    $uid = 0;
    foreach ($filters as $filter) {
        $uid++;
        $finalFilters[$i]['field'] = $filter->getRequestVar();
        $label = ($filter->getRequestVar() == 'cat') ? 'Category' : $filter->getRequestVar();
        $finalFilters[$i]['id'] = $uid;
        $finalFilters[$i]['label'] = ucfirst($label);
        if($filter->getRequestVar() == "price") {
            $finalFilters[$i]['min-price'] = $minPrice;
            $finalFilters[$i]['max-price'] = $maxPrice;
        }
        $k = 0;
        foreach ($filter->getItems() as $item) {

            $k++;
            $optionLabel = strip_tags($item->getLabel());
            $optionValue = $item->getValue();
            $count = $item->getCount();
            $finalFilters[$i]['value'][] = array('label' => $optionLabel, 'value' => $optionValue,'count' => $count);
        }    
       $i++; 
    } 
    $fil = [];
    foreach ($finalFilters as $fill) {
        if (isset($fill['value']))
            $fil[] = $fill;
    }  
    return $fil;     
}

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.