How to upgrade cms page and blocks in Magento 2.
<?php
namespace Pablo\Cms2\Setup;
use Magento\Cms\Model\Page;
use Magento\Cms\Model\PageFactory;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\UpgradeDataInterface;
class UpgradeData implements UpgradeDataInterface
{
/**
* @var PageFactory
*/
private $pageFactory;
/**
* @param PageFactory $pageFactory
*/
private $blockFactory;
public function __construct(
PageFactory $pageFactory,
\Magento\Cms\Model\BlockFactory $blockFactory)
{
$this->pageFactory = $pageFactory;
$this->blockFactory = $blockFactory;
}
/**
* Create page
*
* @return Page
*/
private function createPage()
{
return $this->pageFactory->create();
}
/**
* Upgrades data for a module
*
* @param ModuleDataSetupInterface $setup
* @param ModuleContextInterface $context
* @return void
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
$setup->startSetup();
if (version_compare($context->getVersion(), '2.0.1', '<')) {
$newPageContent = <<<EOD
<h1>Se actualizó la cosa</h1> <img src="http://placehold.it/500x500">
EOD;
$page = $this->createPage()->load('test-home'); /*Selecciona la página por identificador*/
$pageId = $page->getId();
if ($pageId) {
$page->setContent($newPageContent);
$page->save();
}
}
$testBlock = [
'identifier' => 'test-blockkkk',
'title' => 'Test block title',
'content' => '<h1>Test block 2</h1>',
'stores' => [0],
'is_active' => 1,
];
$block = $this->blockFactory->create()->load($testBlock['identifier']);
if($block->getId()){
$block->setTitle($testBlock['title']);
$block->setContent($testBlock['content']);
$block->save();
}else{
$block->setData($testBlock)->save();
}
// Esto funciona
/* $this->blockFactory->create()->setData($testBlock)->save();
$setup->endSetup();*/
}
}