1

I have a Custom module which have customer mapped with certain products , I want to show a custom listing of those products with layered navigation

After Extending product list block in my custom block and changing

public function getLoadedProductCollection()
    {
             return $this->_getProductCollection()->addAttributeToFilter('sku',array('nin'=> $this->getSku()));
    }

On list.phtml

$_productCollection = $block->getLoadedProductCollection();
print_r($_productCollection->getData());
echo"</pre>";

give a Filter collection, But when i Iterate it with

foreach ($_productCollectionTest as $_productTest) {
    echo"<pre>";
    print_r($_productTest->getData());
    echo"</pre>";
}

I get a unfiltered Result

1

You added the filter after the collection was already loaded.

Then in your test code, you fell into the "collection->getData()" trap, that i explained in How to correctly select the first item from a filtered collection?

This results in a second database query as soon as you call getData() and this time, your new filter is applied. But it does not change the _items property, so your previously loaded result is still used for everything else.

By the way, I still did not come across any reasonable use case for this method. It's used internally by load() but probably should not have been public. The core doesn't use it from outside the collection class anywhere as far as I see.

Solution

Clear the collection (which resets _items and marks it as not loaded):

public function getLoadedProductCollection()
{
    $collection = $this->_getProductCollection();
    $collection->clear();
    $collection->addAttributeToFilter('sku',array('nin'=> $this->getSku()));
    return $collection;
}
  • Will this server my purpose of further filtering the collection , after layered filters are already applied – Vishwas Bhatnagar Aug 31 '16 at 16:18
  • 1
    Yes, clear() does not remove the existing filters it just makes the collection reload itself the next time it is iteratred. – Fabian Schmengler Aug 31 '16 at 17:31
  • @fschmengler I am facing an issue of layered navigation for custom collection please advise. I have posted question here link – Nalin Savaliya Nov 8 '16 at 11:30

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.