Create and Edit CMS Content Programmatically in Magento 2 Using Data Upgrade Scripts
If your work environment includes multiple developers and you want eveyone to have the same content on their local environment without having to update the database each time you pull from remote, you should create or edit your CMS content programmatically. To achive this you use data upgrade scripts.
Using data upgrade scripts allows you to add and edit cms pages, static blocks, email templates or even configuration options without the need to log in to admin. It's fairly easy to do once you're all set up with a custom module.
To facilitate the process for you we've created a module that will allow you to start using upgrade scripts in a few simple steps. First, you'll need to get the module and set it up. Head over to the project repo on GH and download it to your app/code directory. Once downloaded install it by running:
bin/magento module:enable RocketWeb_ContentUpdate
bin/magento setup:upgrade
You can either make your changes directly in our module or you can use it to create your own module that extends RocketWeb_ContentUpdate and modify your data upgrade files there. Look into offcial Magento docs if you're not sure how to do that.
Using data upgrade scripts
When you're ready to start adding content open Setup/UpgradeData.php
and scoll down to the bottom of UpgradeData class. If you want you can remove the sample functions we created but we recommend to keep them for reference.
After the last function add your custom functions by copy-pasting one of the existing ones (depending on what you're trying to achieve) and changing their names, content ids etc. Once you add your functions scroll up to public upgrade
function and append an if statement according to the sample below:
if (version_compare($context->getVersion(), '1.0.12') < 0) {
$this->yourCustomFunctionA($helperSetup);
$this->yourCustomFunctionB($helperSetup);
}
Make sure the version number (eg. 1.0.12) is greater the the existing module version in etc/module.xml
. Save your file and open the aforementioned etc/module.xml
to match the version number.
Now all you need to do is run:
bin/magento setup:upgrade
Clear cache and check if your content is present on frontend or in the admin.
You can create as many functions as you want but make sure to update module version number every time you run setup:upgrade. If you need to revert the version number back for some reason you can find it in the database in the setup_upgrade table.
Conclusion
We highly recommend using data upgrade scripts for creating and updating content programmatically if you don't want to manually move it between your environments. It's easy and saves you a lot of time. If you want to learn how to create categories in the same way check out our Use a Magento 2 Data Upgrade Script to Create a Category post.