Adding custom attribute to a Magento CMS page

Sometimes we need to add a custom attribute to a CMS page. I’ll try to describe how we can do this as simply as possible using a custom module with observers.

First of all, you should create your module registration file under app/etc/modules:

<?xml version="1.0"?>
<config>
    <modules>
        <Atwix_CMS>
            <active>true</active>
            <codePool>local</codePool>
        </Atwix_CMS>
    </modules>
</config>

after this, we need to create a folder that contains our own module under app/code/local, in my case it is app/code/local/Atwix/CMS. Next step is to create module’s configuration file (app/code/local/Atwix/CMS/etc/config.xml):

<?xml version="1.0"?>
<config>
    <global>
        <models>
            <atwixcms>
                <class>Atwix_CMS_Model</class>
            </atwixcms>
        </models>
        <events>
            <adminhtml_cms_page_edit_tab_content_prepare_form>
                <observers>
                    <atwix_page_edit_tab_content>
                        <type>singleton</type>
                        <class>Atwix_CMS_Model_Observer</class>
                        <method>cmsField</method>
                    </atwix_page_edit_tab_content>
                </observers>
            </adminhtml_cms_page_edit_tab_content_prepare_form>
        </events>
    </global>
</config>

IMPORTANT: we need to add a column ‘content_custom’ to the ‘cms_page’ table. That can be done using Magento install scripts (read how to create your own installer here)
if you`re using Magento Enterprise, you should add a column ‘content_custom’ to the ‘enterprise_cms_page_revision’ table as well.

and finally, create Observer file (app/code/local/Atwix/CMS/Model/Observer.php):

<?php

class Atwix_CMS_Model_Observer
{
    public function cmsField($observer)
    {
        //get CMS model with data
        $model = Mage::registry('cms_page');
        //get form instance
        $form = $observer->getForm();
        //create new custom fieldset 'atwix_content_fieldset'
        $fieldset = $form->addFieldset('atwix_content_fieldset', array('legend'=>Mage::helper('cms')->__('Custom'),'class'=>'fieldset-wide'));
        //add new field
        $fieldset->addField('content_custom', 'text', array(
            'name'      => 'content_custom',
            'label'     => Mage::helper('cms')->__('Content Custom'),
            'title'     => Mage::helper('cms')->__('Content Custom'),
            'disabled'  => false,
            //set field value
            'value'     => $model->getContentCustom()
        ));

    }
}

That’s all folks. Hope this article is helpful.

Read Part 2: Displaying a custom CMS attribute on the Magento frontend