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
It is becasuse the in filter there is category also so it dont have attribute model so use below function to achieve that