3

I need to create static blocks programmatically. How to assign a block to selected store views?

I've found tutorials about creating static blocks, but they all add the block to all store views, like this:

public function createCmsBlock()
{
 // $this->blockFactory is of type: \Magento\Cms\Model\BlockFactory
 $cmsBlock = $this->blockFactory->create();
 $cmsBlock->setIdentifier('block-identifier')
 ->setTitle('Block Title')
 ->setContent('Block Content')
 ->setIsActive(true)
 ->setStores([0]);
 $cmsBlock->save();
}

As far as I understand the line ->setStores([0]); adds the block to all store views. But how to force it to add our block only to selected store views? And how to retrieve list of such store views?

asked Apr 27, 2017 at 9:56
2
  • 1
    magento.stackexchange.com/questions/127495/…. U need to get current store view & use that. Magento\Store\Model\StoreManagerInterface from u get storeId Commented Apr 27, 2017 at 10:00
  • The ->setStores([0]), add a comma and add your specific store ID here to associate with specific store only. Commented Sep 20, 2019 at 6:03

1 Answer 1

-1

An easy approach to do this is from the Admin Panel:

Content> Blocks> Edit (The Block in Question)

In the edit page you will see it's assigned to all stores/website. Use Ctrl key and select the stores you want it to display.

You can use the same approach to assign different text/language to different store views buy creating another block with same identifier but different content and assigned to different store-views.

answered Apr 18, 2018 at 11:36

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.