ebonik
ebonik

Reputation: 148

Magento CMS Block Collection, can't filter by store id - addStoreFilter([storeid]) not working

How to filter a cms/block (static block) collection ?

This works for cms page:

$model = Mage::getModel('cms/page');
$collection = $model->getCollection()->addStoreFilter(3);

This does NOT work (returns unfiltered collection):

$model = Mage::getModel('cms/block');
$collection = $model->getCollection()->addStoreFilter(3);

I also tried working with the resource models 'cms/block' and 'cms/block_collection', no results.

Why is Magento that inconsequent ?! Sometimes I really start hating Magento for this. Please help.

Upvotes: 4

Views: 6625

Answers (4)

MSQ
MSQ

Reputation: 479

This worked for me to get static block by identifier:

$storeId = 2;
$content = Mage::getModel('cms/block')->setStoreId($storeId)->load('aboutus')->getContent();
echo  $content;

Upvotes: 0

ebonik
ebonik

Reputation: 148

OK, first of all thanks to Mike and oleksii.scarychevskyi. Both answers helped me to get it working. Using this works perfectly and i prefer this one:

$collection = Mage::getModel('cms/block')->getCollection()->addStoreFilter(3, false);

oleksiis solution did also work, I didn't know we can change the select in that way.

Upvotes: 0

oleksii.svarychevskyi
oleksii.svarychevskyi

Reputation: 1106

Try this code:

$collection = Mage::getModel('cms/block')->getCollection();
$select = $collection->getSelect()->join(
    array('block_store' => $collection->getTable('cms/block_store')),
    'main_table.block_id = block_store.block_id',
    array('store_id')
)->where('block_store.store_id IN (?)', array(8));
foreach ($collection as $block) {
   // here you can use $block 
}

You can do the same for cms/page. Just change

cms/block -> cms/page and cms/block_store -> cms/page_store

Upvotes: 4

Mike
Mike

Reputation: 141

What do you exactly mean with unfiltered?

The addStoreFilter has a 2nd parameter to include the admin store as well

addStoreFilter($store, $withAdmin = true)

So if you have any static blocks linked to all stores, these will also be in your collection.

Is this the issue you have?

Upvotes: 6

Related Questions