1

I know that exist a way how to get categories without ObjectManager, but I don't understand how to create the class, which can be used by any model (cause categories I need to implement in different modules and places). I am a newbie in Magento, can you explain step by step where and how I should create a class or simply implement code, but without Object Manager?

1 Answer 1

1

There are multiple ways to create the class but it also depends where you will use it. like

Case1:

If you want to the use the class in phtml file then you can create the Block or viewModels class.

Case2:

If you want to create a class that can be used anywhere then you can create the Trait or Helper Class.

In both the cases, you just need to create the constructor and inject the classes to load & fetch the product & categories data. The same thing will be used into the other classes.

Code Example:

    public function __construct(
        \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory,
        \Magento\Catalog\Model\ProductRepository $productRepository
    ) {
        $this->_categoryCollectionFactory = $categoryCollectionFactory;
        $this->_productRepository = $productRepository;
    }

    public function getCategoryCollection($isActive = true, $level = false, $sortBy = false, $pageSize = false)
    {
        $collection = $this->_categoryCollectionFactory->create();
        $collection->addAttributeToSelect('*');

        // select only active categories
        if ($isActive) {
            $collection->addIsActiveFilter();
        }

        // select categories of certain level
        if ($level) {
            $collection->addLevelFilter($level);
        }

        // sort categories by some value
        if ($sortBy) {
            $collection->addOrderField($sortBy);
        }

        // select certain number of categories
        if ($pageSize) {
            $collection->setPageSize($pageSize);
        }

        return $collection;
    }

    public function getProductById($id)
    {
        return $this->_productRepository->getById($id);
    }

Here is the code that can be used in phtml file. Please note, if you have created the functions in Block class then you use the $block.

$productId = 20; // you can place the current product ID here
$product = $block->getProductById($productId);
$categoryIds = $product->getCategoryIds();
$categories = $block->getCategoryCollection()
->addAttributeToFilter('entity_id', $categoryIds);
foreach ($categories as $category) {
    $category->getName();
}

and if you are above functions in viewModels then you will have to use below:

$viewModel = $block->getData('viewModel');
$productId = 20; // you can place the current product ID here
$product = $viewModel->getProductById($productId);
$categoryIds = $product->getCategoryIds();
$categories = $viewModel->getCategoryCollection()
    ->addAttributeToFilter('entity_id', $categoryIds);
foreach ($categories as $category) {
    $category->getName();
}

Now if you are using the above functions in another class then you will have to create the constructor & create the class object.

   public function __construct(
        \classname $classObjectName
    ) {
        $this->classObjectName = $classObjectName;
    }

Now the common functions can be accessed via above object:

$productId = 20; // you can place the current product ID here
$product = $this->classObjectName->getProductById($productId);
$categoryIds = $product->getCategoryIds();
$categories = $this->classObjectName->getCategoryCollection()
    ->addAttributeToFilter('entity_id', $categoryIds);
foreach ($categories as $category) {
    $category->getName();
}

I hope the information provided above assists you in meeting your needs. I have explained it as thoroughly as I could.

Thankyou

2
  • Thank you so much :D Jan 19 at 8:42
  • I am confused a litttle bit. Where I should place this code? Could you give me example of path? Feb 22 at 6:37

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.