1

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 TheCompany\Theapp\ViewModel;

use Magento\Framework\View\Element\Block\ArgumentInterface;
use Magento\Framework\View\Element\Template;

/**
 * Gets current products Categories
 */
class CategoryLogic extends Template implements ArgumentInterface
{
    /**
     * @param Registry $registry
     * @param Category $categoryModel
     */
    public function __construct(
        \Magento\Framework\Registry $registry,
        \Magento\Catalog\Model\Category $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);

enter image description here

3

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.