I have applied a filter in a PHTML that loads in headers. The filter is below.

In Constructor:

\Magento\Catalog\Model\ResourceModel\Category\Collection $collection

Block Code:

 public function getAllCategories(){
        return $this->collection;


$getAllCategories =  $block->getAllCategories();
$getAllCategories->addAttributeToSelect('*')->addAttributeToFilter('entity_id',array('in' => array($attributVaueArray)))->setOrder('updated_at', 'desc');

But I need to get the same collection in different PHTML without filters. If I use this Model in instructor the filter is applied automatically but I need to reset it. Thanks in advance.


Try below code.

$getAllCategories =  $block->getAllCategories()->load();

You cannot inject the Colection into your class __construct. Try inject CollectionFactory:

In Constructor:

\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $collectionFactory

Block Code:

public function getAllCategories($attributVaueArray) {
    $collection = $this->collectionFactory->create();
    return $collection->addAttributeToSelect('*')
        ->addAttributeToFilter('entity_id',array('in' => array($attributVaueArray)))
        ->setOrder('updated_at', 'desc');

In PHTML: Avoid complex logic inside templates -

$allCategories =  $block->getAllCategories($attributVaueArray);

After making changes - clear caches and generated/code folder

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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