:::: MENU ::::
Posts tagged with: static block

Magento 2 Create CMS Block

Today we discuss about Magento 2 create cms block.This tutorial include how to add new cms block or static block from admin panel, create cms block programmatically. So let start with our example.

Cms block in admin panel

Login to admin panel

Content > Elements > Block

Magento 2 Create CMS Block

Cms block in programmatically

We are creating the cms static block in our installer script. We use block factory to create static block.

namespace QaisarSatti\HelloWorld\Setup;

use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\DB\Ddl\Table;

class InstallSchema implements InstallSchemaInterface {
    private $blockFactory;

    public function __construct(
    \Magento\Cms\Model\BlockFactory $blockFactory
     )
    {

    $this->blockFactory = $blockFactory;
    }  
    public function install( SchemaSetupInterface $setup, ModuleContextInterface $context ) {
        $installer = $setup;

        $installer->startSetup();

       $testBlock = [
         'title' => 'Test block title',
         'identifier' => 'test-block',
         'stores' => [0],
         ‘Content’ => ‘Your content here’
         'is_active' => 1,
         ];
        $this->blockFactory->create()->setData($testBlock)->save();

        $installer->endSetup();
    }
}
Author: Qaisar Satti
Category: Magento 2
Last Modified: August 10, 2018


Magento 2 call static block

Today we learn about how to call static block from phtm fiile,cms page and layout (xml) file. First you have to create a static block from admin panel, go to menu Content , choose Blocks and Click Add New Block button from top right. Every static block have identifier that are unique. You can call static block by identifier. For example our identifier is QaisarSattiTest.Now we use this identifier in phtml file, layout file and cam page.

Phtml:

echo $this->getLayout()->createBlock('Magento\Cms\Block\Block')->setBlockId(QaisarSattiTest)->toHtml();

Layout (xml):

<block class="Magento\Cms\Block\Block" name="footersocial" before="-">                     
      <arguments>
            <argument name="block_id" xsi:type="string">QaisarSattiTest</arguments>
      </arguments>
 </block>

CMS Page:

{{block  id="QaisarSattiTest"}}
Author: Qaisar Satti
Category: Magento 2
Last Modified: July 12, 2018