I have a view model with a method for returning the category names from the current_product (Works in product view page). However it returns null when being used in the catalog view page (catalog_category_view.xml).
ViewModel:
namespace TheCompanyTheappViewModel;
use MagentoFrameworkViewElementBlockArgumentInterface;
use MagentoFrameworkViewElementTemplate;
/**
* Gets current products Categories
*/
class CategoryLogic extends Template implements ArgumentInterface
{
/**
* @param Registry $registry
* @param Category $categoryModel
*/
public function __construct(
MagentoFrameworkRegistry $registry,
MagentoCatalogModelCategory $categoryModel
) {
$this->registry = $registry;
$this->categoryModel = $categoryModel;
}
/**
* Gets current products Categories
*
* @return Category[]
*/
public function getProductCatagory()
{
$product = $this->registry->registry('current_product');
$categories = $product->getCategoryIds(); /*will return category ids array*/
$arr =[];
foreach ($categories as $category) {
$cat = $this->categoryModel->load($category);
$arr[] = $cat->getName();
}
return $arr;
}
}
?>
Phtml:
$viewModel = $block->getData('categoryLogic');
$categories = $viewModel->getCurrentProduct();
var_dump($categories);