Add Custom Field to CMS Page

Sometimes you need to add a custom field to a CMS page. Probably you have done it already in Magento 1. But let's see how you can do it also in Magento 2.

Let's start by creating a custom module under the namespace MageVision. So after creating the module.xml and the registration.php file to register our module as we always do, we will need a setup script to add an new column to the cms_page table. More details about Installing or Upgrading a Database Schema can be found in a previous post

So let's create an InstallSchema class under app/code/MageVision/Blog15/Setup to update the database table cms_page adding a custom_content column.

Afterwards, to display this custom content field in the cms page form in Magento admin, we will need to extend the ui component form that is used. To do that we have to create an xml file called cms_page_form.xml under 

/app/code/MageVision/Blog15/view/adminhtml/ui_component/

and add the following code

The new custom content field is added to the fieldset content and below the default content field. So the custom content field in cms page form looks like

Now let's update the cms page view layout and display the custom content field under the default content field. To update the frontend layout we have to create an xml file called cms_page_view.xml under 

/app/code/MageVision/Blog15/view/frontend/ayout/

and add the following code

As you can see we use a custom block class to display the custom content field. There is no template defined as the _toHtml() function of the block class returns back the value of the custom content field.

The view of our example cms page in store will be

The full example as extension can be found here.

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

Till next time!

DigitalOcean Referral Badge