How to Add a CMS Page Programmatically using Data Patch in Magento 2
In Magento 2.3.x, Magento has introduced the Data Patch interface Magento\Framework\Setup\Patch\DataPatchInterface
to add or modify the EAV data.
In last code snippet, we have seen Customer Attribute creation using Data Patch. In this post, we will see how to add a CMS page programmatically using a data patch in Magento 2.
Add a CMS Page Programmatically
To add a CMS page using data patch create patch file MyCmspage.php under app/code/Vendor/Module/Setup/Patch/Data
directory and add below code.
<?php namespace Vendor\Module\Setup\Patch\Data; use Magento\Cms\Model\PageFactory; use Magento\Framework\Setup\ModuleDataSetupInterface; use Magento\Framework\Setup\Patch\DataPatchInterface; class MyCmspage implements DataPatchInterface { /** * @var ModuleDataSetupInterface */ private $moduleDataSetup; /** * @var PageFactory */ private $pageFactory; /** * @var \Magento\Cms\Model\ResourceModel\Page */ private $pageResource; /** * AddNewCmsPage constructor. * @param ModuleDataSetupInterface $moduleDataSetup * @param PageFactory $pageFactory * @param \Magento\Cms\Model\ResourceModel\Page $pageResource */ public function __construct( ModuleDataSetupInterface $moduleDataSetup, PageFactory $pageFactory, \Magento\Cms\Model\ResourceModel\Page $pageResource ) { $this->moduleDataSetup = $moduleDataSetup; $this->pageFactory = $pageFactory; $this->pageResource = $pageResource; } /** * {@inheritdoc} */ public function apply() { /*delete the existing page*/ $pageIdentifier = 'mypage'; $cmsPageModel = $this->pageFactory->create()->load($pageIdentifier); $this->pageResource->delete($cmsPageModel); $pageData = [ 'title' => 'My Page Title', 'page_layout' => '1column', 'meta_keywords' => '', 'meta_description' => '', 'identifier' => $pageIdentifier, 'content_heading' => '', 'content' => '<h1>Content goes here</h1>', 'layout_update_xml' => '', 'url_key' => $pageIdentifier, 'is_active' => 1, 'stores' => [0], // store_id comma separated 'sort_order' => 0 ]; $this->moduleDataSetup->startSetup(); /* Save CMS Page logic */ $this->pageFactory->create()->setData($pageData)->save(); $this->moduleDataSetup->endSetup(); } /** * {@inheritdoc} */ public static function getDependencies() { return []; } /** * {@inheritdoc} */ public function getAliases() { return []; } }
After adding this class into your module please run below command to create CMS page in database.
php bin/magento setup:upgrade
Hope this post helps you.To receive update about this type of code snippet, please like us on Facebook and follow us on Twitter.
Leave a Comment
(0 Comments)
Useful Magento 2 Articles
Author Info
Chirag
Connect With Me