How to create a module to install a pages and blocks in Magento 2.
<?php
namespace TopGroup\Cms\Setup;
use Magento\Cms\Model\Page;
use Magento\Cms\Model\PageFactory;
use Magento\Framework\Module\Setup\Migration;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
/**
* @codeCoverageIgnore
*/
class InstallData implements InstallDataInterface
{
/**
* Page factory
*
* @var PageFactory
*/
private $pageFactory;
/**
* Init
*
* @param PageFactory $pageFactory
*/
private $blockFactory;
public function __construct(
PageFactory $pageFactory,
\Magento\Cms\Model\BlockFactory $blockFactory)
{
$this->pageFactory = $pageFactory;
$this->blockFactory = $blockFactory;
}
/**
* {@inheritdoc}
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
$setup->startSetup();
$content = <<<EOD
<h1>Sarasa</h1>
EOD;
$cmsPages = [
[
'title' => 'test-home-3',
'page_layout' => '1column',
'identifier' => 'test-home-3',
'content_heading' => 'test-home-3',
'content' => $content,
'is_active' => 1,
'stores' => [0],
'sort_order' => 0
],
[
'title' => 'test',
'page_layout' => '1column',
'identifier' => 'test',
'content_heading' => 'test',
'content' => '<h1>Test</h1>',
'is_active' => 1,
'stores' => [0],
'sort_order' => 0
]
];
/**
* Insert default and system pages
*/
foreach ($cmsPages as $data) {
$page = $this->createPage()->load($data['identifier']);
if($page->getId()){
$page->setTitle($data['title']);
$page->setPageLayout($data['page_layout']);
$page->setLayoutUpdateXml($data['layout_update_xml']);
$page->setCustomLayoutUpdateXml($data['custom_layout_update_xml']);
$page->setContentHeading($data['content_heading']);
$page->setContent($data['content']);
$page->save();
}else{
$page->setData($data)->save();
}
}
/* Sección bloques */
$content = <<<EOD
<h1>Your content</h1>
EOD;
$contentSubFooter = <<<EOD
<h1>Sub footer</h1>
EOD;
$cmsBlocks = [
[
'identifier' => 'footer_links_block',
'title' => 'Footer Links',
'content' => $content,
'stores' => [0],
'is_active' => 1,
],
[
'identifier' => 'sub-footer',
'title' => 'Sub Footer',
'content' => $contentSubFooter,
'stores' => [0],
'is_active' => 1,
]
];
foreach ($cmsBlocks as $data) {
$block = $this->blockFactory->create()->load($data['identifier']);
if($block->getId()){
$block->setTitle($data['title']);
$block->setContent($data['content']);
$block->save();
}else{
$block->setData($data)->save();
}
}
} /*Install Function*/
/**
* Create page
*
* @return Page
*/
public function createPage()
{
return $this->pageFactory->create();
}
}