Tuesday, October 30, 2012

Add a new field to the store view

Here is the clear way to add a new field on the store view in Magento.
In order to do this you should create a new extension.
For the purpose of this demo I will use the 'namespace' Easylife. replace it with your own namespace if you want.
The extension is named Core because I'm overriding something in the core. You can name it how ever you want. Here are the files that need to be created:

app/code/local/Easylife/Core/etc/config:
<?xml version="1.0"?>
<config>
    <modules>
        <Easylife_Core>
            <version>0.0.1</version>
        </Easylife_Core>
    </modules>
    <global>
        <resources>
            <easylife_core_setup>
                <setup>
                    <module>Easylife_Core</module>
                </setup>
            </easylife_core_setup>
        </resources>
        <blocks>
            <adminhtml>
                <rewrite>
                    <system_store_edit_form>Easylife_Core_Block_Adminhtml_System_Store_Edit_Form</system_store_edit_form>
                </rewrite>
            </adminhtml>
        </blocks>
    </global>
</config>
app/code/local/Easylife/Core/sql/easylife_core_setup/mysql4-install-0.0.1.php
<?php 
$this->startSetup();
$this->run("ALTER TABLE `{$this->getTable('core/store')}` ADD COLUMN `custom` VARCHAR(255)");//change the name and type of the column if you need.
$this->endSetup();
app/code/local/Easylife/Core/Block/Adminhtml/System/Store/Edit/Form.php - this overrides the admin block.
<?php 
class Easylife_Core_Block_Adminhtml_System_Store_Edit_Form extends Mage_Adminhtml_Block_System_Store_Edit_Form{
    protected function _prepareForm(){
        parent::_prepareForm();
        if (Mage::registry('store_type') == 'store'){
            $storeModel = Mage::registry('store_data');
            $fieldset = $this->getForm()->getElement('store_fieldset');
            $fieldset->addField('custom', 'text', array(
                    'name'      => 'store[custom]',
                    'label'     => Mage::helper('core')->__('Custom'),
                    'required'  => true,//or false
                    'value'        => $storeModel->getData('custom') 
                ));
        }
        return $this;
    }
}
In order to activate your module you need this file
app/etc/modules/Easylife_Core.xml
<?xml version="1.0"?>
<config>
    <modules>
        <Easylife_Core>
            <active>true</active>
            <codePool>local</codePool>
            <depends>
                <Mage_Core/>
            </depends>
        </Easylife_Core>
    </modules>
</config>
Enjoy.
Marius.