How to Add CMS Block in Magento2 programatically.
I want to add a cms block in app/code insstead of app/design using layout or xml files.
Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform. It only takes a minute to sign up.
Sign up to join this communityYou can create in setup script or controller.
public $blockFactory;
public $blockRepository;
public function __construct(
PageFactory $pageFactory,
\Magento\Cms\Model\BlockFactory $blockFactory,
\Magento\Cms\Model\BlockRepository $blockRepository
)
{
$this->resultPageFactory = $resultPageFactory;
$this->blockFactory = $blockFactory;
$this->blockRepository = $blockRepository;
}
yourfunction()
{
$Page = [
'title' => 'Your page title',
'identifier' => 'your-page',
'stores' => [0],
'is_active' => 1,
'content' => 'test content',
'page_layout' => '1column'
];
$this->blockFactory->create()->setData($Page)->save();
}
Create a module like app/code/VendorName/ModuleName/
then create layout file default.xml
at app/code/VendorName/ModuleName/view/frontend/layout
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="footer">
<block class="Magento\Cms\Block\Block" name="Promo">
<arguments>
<argument name="block_id" xsi:type="string">{BlockIdenfier}</argument>
</arguments>
</block>
</referenceContainer>
</body>
</page>
Replace {BlockIdenfier}
with your cms block identifier.