How to build CMS page by source code in Magento 2

In Magento you can build a CMS pages in admin>CMS>Page. Moreover, you can also build it by setup or improve module.

In this article, you can know how to add CMS page in to Magento 2 by setup script through precise steps:

Step 1: build UpgradeData.php File

Step 2: Setup the module version

Step 3: Run setup script through command line

Step 1: build UpgradeData.php File

File directory:

app/code/Webnexs/Example/Setup/UpgradeData.php
<?php

namespace Vendor\Module\Setup;

use Magento\Framework\Setup\UpgradeDataInterface;

use Magento\Framework\Setup\ModuleContextInterface;

use Magento\Framework\Setup\ModuleDataSetupInterface;

/**

* @codeCoverageIgnore

*/

class UpgradeData implements UpgradeDataInterface

{

   /**

    * @var \Magento\Cms\Model\PageFactory

    */

   protected $_pageFactory;

  /**

    * Construct

    *

    * @param \Magento\Cms\Model\PageFactory $pageFactory

    */

   public function __construct(

       \Magento\Cms\Model\PageFactory $pageFactory

   ) {

       $this->_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('new-cms-page')

               ->setIsActive(true)

               ->setPageLayout('1column')

               ->setStores(array(0))

               ->setContent('Hello magento 2')

               ->save();

       }

  $setup->endSetup();

   }

}

Step 2: Setup the module version

Open etc/module.xml file, you need to set your module version in set up_version elements.

Step 3: Run setup script through command line

Finally open terminal and run command lines

bin/magento setup:upgrade

Check the result on admin>CMS>pages

I hope the following steps help you to build CMS page by source code in Magento 2

Last Update: April 9, 2018  

February 14, 2018   166   Nandini R    Tips And Tricks    
Total 2 Votes:
0

Tell us how can we improve this post?

+ = Verify Human or Spambot ?

Leave a Reply

Your email address will not be published. Required fields are marked *

Facebook
Google+
http://www.webnexs.com/blog/kb/build-cms-page-source-code-magento-2
Twitter
LinkedIn