I am working in Magento 2 and I am needing to create multiple CMS pages all at one time. I am trying to set up an Install script to do this all at once. Every tutorial and search that I look up shows how to create one CMS page programmatically but I've searched everywhere and haven't found a single one showing how to create multiple at the same time. Is this even possible?
I have created a custom module with an InstallData script that looks like this:
namespace <VendorName>\<ModuleName>\Setup;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
class InstallData implements \Magento\Framework\Setup\InstallDataInterface
{
private $_pageFactory;
public function __construct(\Magento\Cms\Model\PageFactory $pageFactory)
{
$this->_pageFactory = $pageFactory;
}
public function install(ModuleDataSetupInterface $setup,
ModuleContextInterface $context
) {
$setup->startSetup();
$page = $this->_pageFactory->create();
$page1 = $page->load('page1', 'identifier');
if ($page1->getId()) {
$page1->setContent('<h1>This is it!</h1>')->save();
} else {
$page->setTitle('Page 1')
->setIdentifier('page1')
->setIsActive(true)
->setPageLayout('1column')
->setStores(array(0))
->setContent('<h1>This is it!</h1>')
->save();
}
$page2 = $page->load('page2', 'identifier');
if ($page2->getId()) {
$page2->setContent('<h1>This is it!</h1>')->save();
} else {
$page->setTitle('Page 2')
->setIdentifier('page2')
->setIsActive(true)
->setPageLayout('1column')
->setStores(array(0))
->setContent('<h1>This is it!</h1>')
->save();
}
$page3 = $page->load('page3', 'identifier');
if ($page3->getId()) {
$page3->setContent('<h1>This is it!</h1>')->save();
} else {
$page->setTitle('Page 3')
->setIdentifier('page3')
->setIsActive(true)
->setPageLayout('1column')
->setStores(array(0))
->setContent('<h1>This is it!</h1>')
->save();
}
$setup->endSetup();
}
}
This does not throw any errors, but when I enable the module it only creates the first page 'page1' and doesn't create any of the others. Please help.