I’m starting series of short blog posts to share solutions for common Magento 2 problems. In first one I’m going to show how to add CMS Page programmatically in setup scripts.
Use following steps to create CMS page:
1. Create Setup/UpgradeData.php file inside your module.
2. Create UpgradeData class, add required model using dependency injection and then add code which adds new CMS page. Full class below:
_pageFactory = $pageFactory; } /** * @param ModuleDataSetupInterface $setup * @param ModuleContextInterface $context */ public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context) { $setup->startSetup(); if (version_compare($context->getVersion(), '1.1') < 0) { $page = $this->_pageFactory->create(); $page->setTitle('Example CMS page') ->setIdentifier('example-cms-page') ->setIsActive(true) ->setPageLayout('1column') ->setStores(array(0)) ->setContent('Lorem ipsum dolor sit amet, consectetur adipiscing elit.') ->save(); } $setup->endSetup(); } }
3. Change your module version in setup_version attribute in etc/module.xml file, in this case it should be 1.1.
4. Run database upgrade script:
bin/magento setup:upgrade
That’s it, your CMS page should be now visible in Magento 2 backend.
Hi Wojtek,
Thank you for your article, it is really helpful for developers who want to jump into Magento 2. Few notes I would like to share regarding the article:
1. It is better to pass \Magento\Cms\Model\PageFactory $pageFactory into __construct() method. The $pageFactory will then create new instance of the \Magento\Cms\Model\Page class.
2. There is no need to copy $setup variable into $installer. The $installer variable was introduced back in Magento 1. Let’s leave it there.
Thank you for your post.
Max, thanks for feedback, it makes sense, I updated snippets with proposed changes.
I was looking for code sample which adds CMS page in core code and I found Magento\Cms\Model\Page instantiated by object manager – it looks this part was not refactored yet.
Good catch about $installer :-)