Inserting multiple CMS blocks into a product collection
-
01-10-2020 - |
Question
My objective is to allow CMS blocks to be added to a category's product collection at various places via the visual merchandiser.
I created a custom table which is similar to catalog_category_product
except referencing categories and blocks with a relevance/position field, and have created some dummy data with a position that might look like this:
1: Product 1, 2: Product 2, 3: Block 1, 4: Product 3, 5: Block 2
I.e. three products and two blocks forming five entities.
I am interested to know whether I can swap the product collection that categories use by default out for a custom Varien_Data_Collection
(_Db
?) containing both products and CMS blocks together. If this is possible, I could then hopefully pass the Frankenstein collection into the "toolbar" pager and have it correctly perform pagination as per normal for the category pages.
Question: Is it possible to have a collection containing multiple entity types?
The reason I'm looking at doing this is that the pagination won't really work correctly unless I pass it a final entity collection to paginate. E.g. If my first page had 5 products and 3 blocks and I set the page size to 5 to prevent 8 products from loading then the next page would then load 5 products, but it may actually need to load 8 products if no static blocks exist in the page.
I'm having a surprising amount of luck by creating "fake products" in the collection with an observer like so:
/** @var Mage_Cms_Model_Resource_Block_Collection $blockCollection */
foreach ($blockCollection as $block) { /** @var Mage_Cms_Model_Block $block */
$frankensteinProduct = $productCollection
->getNewEmptyItem()
->addData($block->getData())
->setData('product_or_block', 'block')
->setData('entity_id', 'block_' . $block->getId());
$productCollection->addItem($frankensteinProduct);
}
Is this the right approach to be taking?
Solution
That's a good question I faced a similar issue a while back when requirement was to be able to add advert panels to show up between the product list.
I did not even try to do a multiple type collection like what you're doing because I assumed it would be hard to implement and the product list highly depends on the fact that objects are products.
What I ended up doing was to create my own product type that I would use to deal with to create my advert panels.
Apart from image, name and text I didn't need much so that was enough in my case. I made it behaves like CMS block basically.