How to Create a CMS Page using Data Patch

Do you want to create a CMS page programmatically and not directly in admin? That can easily be done using a data patch to create that page. Let's see together how easily you can do that!

As is well known in Magento 2.3.x, you can easily apply data changes using data patches. This is what we will also use in this post to create a CMS page. In the data patch class you can see below, the apply() function is the one that includes the code which is executed by running the CLI command, bin/magento setup:upgrade. In this function we create a sample CMS page.

As you can see above, our class implements 2 interfaces, the DataPatchInterface and the PatchRevertableInterface. The DataPatchInterface is the standard one for a data patch class, requests to have in our class the functions apply(), getDependencies() and getAliases(). Additionally to the interface DataPatchInterface we added also the PatchRevertableInterface. This requests to have the revert() function in our class, which is responsible to revert the data changes that the apply() function brought, when we uninstall the module. To revert our data patch in our case we need to execute the following command.

bin/magento module:uninstall --non-composer MageVision_Blog70

So now if you execute the command bin/magento setup:upgrade, our data patch will be executed and a CMS page will be created as you can see below.

Feel free to share this post and ask your questions in the comments below.

Till next time!