skip to Main Content

I am creating api to get filterable attribute for specific category in magento 2.

We see in category page for layered navigation. I want to achieve exact same data in api.

  $objectManager = MagentoFrameworkAppObjectManager::getInstance();

    $filterableAttributes = $objectManager->get(MagentoCatalogModelLayerCategoryFilterableAttributeList::class);

    $appState = $objectManager->get(MagentoFrameworkAppState::class);
    $layerResolver = $objectManager->get(MagentoCatalogModelLayerResolver::class);
    $filterList = $objectManager->create(
    MagentoCatalogModelLayerFilterList::class,
        [
            'filterableAttributes' => $filterableAttributes
        ]
    );

    $category_id = 41;

    // $appState->setAreaCode('frontend');
    $layer = $layerResolver->get();
    $layer->setCurrentCategory($category_id);
    $filters = $filterList->getFilters($layer);

    $finalFilters = [];
    $data = array();
    $i = 0;
    foreach ($filters as $filter) {
        if ($filter->getItemsCount()) {
            $name = $filter->getName();
            foreach ($filter->getItems() as $item) {

                if($item->getFilter()->getAttributeModel()->getAttributeCode() == 'price'){

                    $finalFilters[$name][$i]['name'] = $this->Helper->removeHTML($item->getLabel()->getArguments());
                    $finalFilters[$name][$i]['value'] = $item->getValue();
                    $finalFilters[$name][$i]['code'] = $item->getFilter()->getAttributeModel()->getAttributeCode();         
                }
                else{

                    $finalFilters[$name][$i]['name'] = $item->getLabel();
                    $finalFilters[$name][$i]['value'] = $item->getValue();
                    $finalFilters[$name][$i]['code'] = $item->getFilter()->getAttributeModel()->getAttributeCode();
                }
                $i++;
            }
        }
    }

But getting following error.

Exception #0 (MagentoFrameworkExceptionLocalizedException): The attribute model is not defined.

2

Answers


  1. It is becasuse the in filter there is category also so it dont have attribute model so use below function to achieve that

    public function filters($categoryId)
        {
            $categoryLayer = $this->layerResolver->get()->setCurrentCategory($categoryId);
            $category      = $this->getCategory();
    
            $filterList       = new FilterList($this->objectManager, $this->fill);
            $filterAttributes = $filterList->getFilters($categoryLayer);
            $filterArray      = [];
    
            $i = 0;
    
            foreach ($filterAttributes as $filter) {
                $attributeLabel = (string) $filter->getName();
                $attributeCode  = (string) $filter->getRequestVar();
                $items          = $filter->getItems();
                $filterValues   = [];
    
                $j = 0;
    
                foreach ($items as $item) {
                    if ($attributeCode == 'cat') {
                        $filterValues[$j]['display'] = strip_tags($item->getLabel());
                        $filterValues[$j]['value']   = $item->getValue();
                    } elseif ($category->getIsAnchor()) {
                        if ($filter->getAttributeModel()
                        && $filter->getAttributeModel()->getFrontendInput() == 'price') {
                            $filterValues[$j]['min_price'] = $filter->getLayer()->getProductCollection()->getMinPrice();
                            $filterValues[$j]['max_price'] = $filter->getLayer()->getProductCollection()->getMaxPrice();
                            break;
                        }
    
                        $filterValues[$j]['display'] = strip_tags($item->getLabel());
                        $filterValues[$j]['value']   = $item->getValue();
    
                        // Get Swatches.
                        $swatchesValues = $this->getSwatches($filter, $item, $j);
                        if (!empty($swatchesValues)) {
                            $filterValues[$j]['swatch_value'] = $swatchesValues['swatch_value'];
                            $filterValues[$j]['swatch_type']  = $swatchesValues['swatch_type'];
                        }
                    }
                    $j++;
                }
    
                if (!empty($filterValues)) {
                    $filterArray['available_filter'][$attributeCode]['label']  = $attributeLabel;
                    $filterArray['available_filter'][$attributeCode]['values'] = $filterValues;
                }
                $i++;
            }
    
            return [$filterArray];
        }//end filters()
    Login or Signup to reply.
  2. <?php
    namespace ExampleExtendedApiModel;
    
    use ExampleExtendedApiApiFiltersInterface;
    
    class FiltersManagement implements FiltersInterface
    {
    
      protected $_request;
      protected $_filterableAttributeList;
      protected $_layerResolver;
      protected $_filterList;
      protected $_storeManagerInterface;
      protected $_response;
      protected $_redirFactory;
    
      public function __construct(
        MagentoCatalogGraphQlModelResolverLayerFilterableAttributesListFactory $filterableAttributeList,
        MagentoCatalogModelLayerFilterListFactory $filterList,
        MagentoStoreModelStoreManagerInterface $storeManagerInterface,
        MagentoCatalogModelLayerResolver $layerResolver,
        MagentoFrameworkWebapiRestRequest $request
      )
      {
        $this->_filterList                      = $filterList;
        $this->_filterableAttributeList         = $filterableAttributeList;
        $this->_layerResolver                   = $layerResolver;
        $this->_request                         = $request;
        $this->_storeManagerInterface           = $storeManagerInterface;
      }
    
      /**
        * GET  review by its ID
        *
        * @api
        * @return array
        * @throws MagentoFrameworkExceptionNoSuchEntityException
        *
        */
      public function getLayeredFilters()
      {
        $categoryId   = $this->_request->getParam('categoryId');
        $layer        = $this->_layerResolver->get();
    
    
        $layerType = "search";
        if ($categoryId){
          $layer->setCurrentCategory($categoryId);
          $layerType = "category";
        }
    
        $filterArray['store_id']  = $this->_storeManagerInterface->getStore()->getId();
        $filterableAttributesList = $this->_filterableAttributeList->create($layerType);
    
        $filterList = $this->_filterList->create(['filterableAttributes' => $filterableAttributesList]);
        $filters    = $filterList->getFilters($layer);
        $i = 0;
        foreach($filters as $filter)
        {
            // Don't show options with no items
          if (! $filter->getItemsCount()) {continue;}
    
          $availablefilter = (string)$filter->getName();
          $items           = $filter->getItems();
          $filterValues    = array();
    
          $j = 0;
          foreach($items as $item)
          {
            $filterValues[$j]['display'] = strip_tags($item->getLabel());
            $filterValues[$j]['value']   = $item->getValue();
            $filterValues[$j]['count']   = $item->getCount(); //Gives no. of products in each filter options
            $filterValues[$j]['url']     = $item->getUrl();   //Gives filter url.
            $j++;
          }
    
          if(!empty($filterValues) && count($filterValues)>1)
          {
            $filterArray['availablefilter'][$availablefilter] =  $filterValues;
          }
          $i++;
    
        }
    
        if (!isset($filterArray["availablefilter"])) {
          $filterArray['availablefilter'] = "No filters to show.";
        }
    
        header("Content-Type: application/json; charset=utf-8");
        $this->response = json_encode($filterArray);
        print_r($this->response,false);
        die();
      }
    
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search