简体   繁体   中英

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.

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?

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

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.

This worked for me to get static block by identifier:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM