PHP Magento Tips

Add Store wise Custom Background Image For Different Pages In Magento

Rate this posting:
{[['']]}

With Previous tutorial you can set Custom Festival Background Image for your Magento Store with predefined start Date and End Date. In this tutorial, you will learn how to add Custom Background Image for different Pages for your Magento Store.

Download




Step 1: Create Extension Initialization file. Create file in app/etc/modules/Vijay_CustomBackground.xml and add below code in it.

<?xml version="1.0"?>
<config>
    <modules>
        <Vijay_CustomBackground>
            <active>true</active>
            <codePool>community</codePool>
            <depends>
                <Mage_Core />
             </depends>
        </Vijay_CustomBackground>
    </modules>
</config>
Step 2: Create Extension Config.xml file. Create file in app/code/community/Vijay/CustomBackground/etc/config.xml and add below code in it.

<?xml version="1.0"?>
<config>
    <modules>
        <Vijay_CustomBackground>
            <version>1.0.0</version>
        </Vijay_CustomBackground>
    </modules>
    <global>
        <resources>
            <vijay_custombackground_setup>
                <setup>
                    <module>Vijay_CustomBackground</module>
                    <class>Vijay_CustomBackground_Model_Resource_Setup</class>
                </setup>
            </vijay_custombackground_setup>
        </resources>
        <blocks>
            <vijay_custombackground>
                <class>Vijay_CustomBackground_Block</class>
            </vijay_custombackground>
        </blocks>
        <helpers>
            <vijay_custombackground>
                <class>Vijay_CustomBackground_Helper</class>
            </vijay_custombackground>
        </helpers>
        <models>
            <vijay_custombackground>
                <class>Vijay_CustomBackground_Model</class>
                <resourceModel>vijay_custombackground_resource</resourceModel>
            </vijay_custombackground>
            <vijay_custombackground_resource>
                <class>Vijay_CustomBackground_Model_Resource</class>
                <entities>
                    <background>
                        <table>vijay_custombackground_background</table>
                    </background>
                    <background_store>
                        <table>vijay_custombackground_background_store</table>
                    </background_store>
                </entities>
            </vijay_custombackground_resource>
        </models>
    </global>
    <adminhtml>
        <layout>
            <updates>
                <vijay_custombackground>
                    <file>vijay_custombackground.xml</file>
                </vijay_custombackground>
            </updates>
        </layout>
        <translate>
            <modules>
                <Vijay_CustomBackground>
                    <files>
                        <default>Vijay_CustomBackground.csv</default>
                    </files>
                </Vijay_CustomBackground>
            </modules>
        </translate>
        <global_search>
            <background>
                <class>vijay_custombackground/adminhtml_search_background</class>
                <acl>vijay_custombackground</acl>
            </background>
        </global_search>
    </adminhtml>
    <admin>
        <routers>
            <adminhtml>
                <args>
                    <modules>
                        <Vijay_CustomBackground before="Mage_Adminhtml">Vijay_CustomBackground_Adminhtml</Vijay_CustomBackground>
                    </modules>
                </args>
            </adminhtml>
        </routers>
    </admin>
    <frontend>
        <layout>
            <updates>
                <vijay_custombackground>
                    <file>vijay_custombackground.xml</file>
                </vijay_custombackground>
            </updates>
        </layout>
    </frontend>
    <default>
        <vijay_custombackground>
            <general>
                <is_enabled>1</is_enabled>
            </general>
        </vijay_custombackground>
 </default>
</config>
Step 3: Create system.xml file. Create file in app/code/community/Vijay/CustomBackground/etc/system.xml and add below code in it.

<?xml version="1.0"?>
<config>
 <tabs>
        <vijay translate="label" module="vijay_custombackground">
            <label>Custom Background</label>
            <sort_order>320</sort_order>
        </vijay>
    </tabs>
    <sections>
        <vijay_custombackground translate="label" module="vijay_custombackground">
            <label>Custom Background Settings</label>
            <tab>vijay</tab>
            <frontend_type>text</frontend_type>
            <sort_order>150</sort_order>
            <show_in_default>1</show_in_default>
            <show_in_website>1</show_in_website>
            <show_in_store>1</show_in_store>
            <groups>
                <general translate="label">
                    <label>General Settings</label>
                    <frontend_type>text</frontend_type>
                    <sort_order>10</sort_order>
                    <show_in_default>1</show_in_default>
                    <show_in_website>1</show_in_website>
                    <show_in_store>1</show_in_store>
                    <fields>
                        <is_enabled translate="label">
                            <label>Is Enabled</label>
                            <frontend_type>select</frontend_type>
                            <source_model>adminhtml/system_config_source_yesno</source_model>
                            <sort_order>10</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </is_enabled>
                    </fields>
                </general>
            </groups>
        </vijay_custombackground>
    </sections>
</config>

Step 4: Create adminhtml.xml file. Create file in app/code/community/Vijay/CustomBackground/etc/adminhtml.xml and add below code in it.

<?xml version="1.0"?>
<config>
    <acl>
        <resources>
            <admin>
                <children>
                    <system>
                        <children>
                            <config>
                                <children>
                                    <vijay_custombackground translate="title" module="vijay_custombackground">
                                        <title>CustomBackground</title>
                                    </vijay_custombackground>
                                </children>
                            </config>
                        </children>
                    </system>
                    <vijay_custombackground translate="title" module="vijay_custombackground">
                        <title>Custom Background</title>
                        <children>
                            <background translate="title" module="vijay_custombackground">
                                <title>Background</title>
                                <sort_order>0</sort_order>
                            </background>
                        </children>
                    </vijay_custombackground>
                </children>
            </admin>
        </resources>
    </acl>
    <menu>
        <vijay_custombackground translate="title" module="vijay_custombackground">
            <title>Custom Background</title>
            <sort_order>45</sort_order>
            <children>
                <background translate="title" module="vijay_custombackground">
                    <title>Background</title>
                    <action>adminhtml/custombackground_background</action>
                    <sort_order>0</sort_order>
                </background>
            </children>
        </vijay_custombackground>
    </menu>
</config>

Step 5: Create file in app/code/community/Vijay/CustomBackground/sql/vijay_custombackground_setup/install-1.0.0.php and add below code in it.

<?php
$this->startSetup();
$table = $this->getConnection()
    ->newTable($this->getTable('vijay_custombackground/background'))
    ->addColumn(
        'entity_id',
        Varien_Db_Ddl_Table::TYPE_INTEGER,
        null,
        array(
            'identity'  => true,
            'nullable'  => false,
            'primary'   => true,
        ),
        'Background ID'
    )
    ->addColumn(
        'background_name',
        Varien_Db_Ddl_Table::TYPE_TEXT, 255,
        array(
            'nullable'  => false,
        ),
        'Background Name'
    )
    ->addColumn(
        'background_target',
        Varien_Db_Ddl_Table::TYPE_TEXT, 255,
        array(
            'nullable'  => false,
        ),
        'Background Target'
    )
 ->addColumn(
        'background_custom_target',
        Varien_Db_Ddl_Table::TYPE_TEXT, 255,
        array(),
        'Background Custom Target'
    )
    ->addColumn(
        'background_target_type',
        Varien_Db_Ddl_Table::TYPE_INTEGER, null,
        array(
            'nullable'  => false,
        ),
        'Background Target Type'
    )
    ->addColumn(
        'background_target_id',
        Varien_Db_Ddl_Table::TYPE_TEXT, '64k',
        array(),
        'Background Target Page'
    )
 ->addColumn(
        'background_category_id',
        Varien_Db_Ddl_Table::TYPE_TEXT, '64k',
        array(),
        'Background Target Category'
    )
    ->addColumn(
        'background',
        Varien_Db_Ddl_Table::TYPE_TEXT, 255,
        array(),
        'Background'
    )
    ->addColumn(
        'background_color',
        Varien_Db_Ddl_Table::TYPE_TEXT, 255,
        array(),
        'Background Color'
    )
    ->addColumn(
        'background_repeat',
        Varien_Db_Ddl_Table::TYPE_TEXT, 255,
        array(),
        'Background Repeat'
    )
    ->addColumn(
        'background_position',
        Varien_Db_Ddl_Table::TYPE_TEXT, 255,
        array(),
        'Background Position'
    )
    ->addColumn(
        'background_attachment',
        Varien_Db_Ddl_Table::TYPE_TEXT, 255,
        array(),
        'Background Attachment'
    )
    ->addColumn(
        'background_size',
        Varien_Db_Ddl_Table::TYPE_TEXT, 255,
        array(),
        'Background Size'
    )
    ->addColumn(
        'background_origin',
        Varien_Db_Ddl_Table::TYPE_TEXT, 255,
        array(),
        'Background Origin'
    )
    ->addColumn(
        'background_clip',
        Varien_Db_Ddl_Table::TYPE_TEXT, 255,
        array(),
        'Background Clip'
    )
    ->addColumn(
        'background_additional_style',
        Varien_Db_Ddl_Table::TYPE_TEXT, 255,
        array(),
        'Background Additional Style'
    )
    ->addColumn(
        'status',
        Varien_Db_Ddl_Table::TYPE_SMALLINT, null,
        array(),
        'Enabled'
    )
    ->addColumn(
        'updated_at',
        Varien_Db_Ddl_Table::TYPE_TIMESTAMP,
        null,
        array(),
        'Background Modification Time'
    )
    ->addColumn(
        'created_at',
        Varien_Db_Ddl_Table::TYPE_TIMESTAMP,
        null,
        array(),
        'Background Creation Time'
    ) 
    ->setComment('Background Table');
$this->getConnection()->createTable($table);
$table = $this->getConnection()
    ->newTable($this->getTable('vijay_custombackground/background_store'))
    ->addColumn(
        'background_id',
        Varien_Db_Ddl_Table::TYPE_SMALLINT,
        null,
        array(
            'nullable'  => false,
            'primary'   => true,
        ),
        'Background ID'
    )
    ->addColumn(
        'store_id',
        Varien_Db_Ddl_Table::TYPE_SMALLINT,
        null,
        array(
            'unsigned'  => true,
            'nullable'  => false,
            'primary'   => true,
        ),
        'Store ID'
    )
    ->addIndex(
        $this->getIdxName(
            'vijay_custombackground/background_store',
            array('store_id')
        ),
        array('store_id')
    )
    ->addForeignKey(
        $this->getFkName(
            'vijay_custombackground/background_store',
            'background_id',
            'vijay_custombackground/background',
            'entity_id'
        ),
        'background_id',
        $this->getTable('vijay_custombackground/background'),
        'entity_id',
        Varien_Db_Ddl_Table::ACTION_CASCADE,
        Varien_Db_Ddl_Table::ACTION_CASCADE
    )
    ->addForeignKey(
        $this->getFkName(
            'vijay_custombackground/background_store',
            'store_id',
            'core/store',
            'store_id'
        ),
        'store_id',
        $this->getTable('core/store'),
        'store_id',
        Varien_Db_Ddl_Table::ACTION_CASCADE,
        Varien_Db_Ddl_Table::ACTION_CASCADE
    )
    ->setComment('Backgrounds To Store Linkage Table');
$this->getConnection()->createTable($table);
$this->endSetup();

Step 6: Create file in app/code/community/Vijay/CustomBackground/Block/Background.php and add below code in it.

<?php
class Vijay_CustomBackground_Block_Background extends Mage_Core_Block_Template
{
    
    public function getBackground()
    {
        if(!$this->getData('current_vijay_custombackground')){
         if (Mage::helper('vijay_custombackground/page')->isCmsPage() && !Mage::helper('vijay_custombackground/page')->isHomePage()) {
            $background = Mage::getModel('vijay_custombackground/background')
                        ->getCollection()
                        ->addFieldToFilter('status',1)
                        ->addStoreFilter(Mage::app()->getStore())
                        ->addFieldToFilter('background_target_type',Vijay_CustomBackground_Model_Background::TARGET_CMS)
                        ->addFieldToFilter('background_target_id',array('regexp'=>'(^|,)'.Mage::getSingleton('cms/page')->getIdentifier().'(,|$)'))
                        ->getFirstItem();      
        } else {
         $background = Mage::helper('vijay_custombackground')->getCurrentBackground();
        }
            
            $this->setData('current_vijay_custombackground',$background);
        }
        return $this->getData('current_vijay_custombackground');
    }
            
    public function canShow() {
     if (!$this->getConfig()->isEnabled()) {
            return false;
        } else {
         return true;
        }
   }
 
    public function isBackgroundNeeded()
    {
        return (bool)$this->getBackground();
    }
    
 public function getStyleOptions(){
        $result = array();
        $background = $this->getBackground();
        if(strlen($background->getBackgroundColor())){
            $result['backgroundColor'] = $background->getBackgroundColor();
        }
        
        if(strlen($background->getBackground())){
            $result['backgroundImage'] = 'url('.Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA).'background/image'.$background->getBackground().')';
        }
            
       /*if($background->getRepeatX() && $background->getRepeatY()){
            $result['backgroundRepeat'] = 'repeat';
        } elseif($background->getRepeatX()){
            $result['backgroundRepeat'] = 'repeat-x';
        } elseif($background->getRepeatY()){
            $result['backgroundRepeat'] = 'repeat-y';
        }*/
        if($background->getBackgroundRepeat()){
            $result['backgroundRepeat'] = $background->getBackgroundRepeat();
        }
        
  if($background->getBackgroundPosition()){
            $result['backgroundPosition'] = $background->getBackgroundPosition();
        }
  
  if($background->getBackgroundAttachment()){
            $result['backgroundAttachment'] = $background->getBackgroundAttachment();
        }
  
  if($background->getBackgroundSize()){
            $result['backgroundSize'] = $background->getBackgroundSize();
        }
  
  if($background->getBackgroundOrigin()){
            $result['backgroundOrigin'] = $background->getBackgroundOrigin();
        }
  
  if($background->getBackgroundClip()){
            $result['backgroundClip'] = $background->getBackgroundClip();
        }
  
         if(strlen($background->getBackgroundAdditionalStyle())){
             foreach(explode(';',$background->getBackgroundAdditionalStyle()) as $pair){
                 if(!stristr($pair, ':'))
                         continue;
                 list($key,$value) = explode(':',$pair);
                 $result[$key] = $value;
             }
         }
         return $result;
    }

    public function getTargetElement()
    {
        $background = $this->getBackground();
  
  if ($background->getBackgroundTarget() == 'custom'){
   return $background->getBackgroundCustomTarget();
  } else {
   return $background->getBackgroundTarget();
  }
    }
 
  /**
     * @return Vijay_CustomBackground_Helper_Config
     */
    public function getConfig()
    {
        return Mage::helper('vijay_custombackground/config');
    }
 
}

Step 7: Create file in app/code/community/Vijay/CustomBackground/Block/Adminhtml/Background.php and add below code in it.

<?php

class Vijay_CustomBackground_Block_Adminhtml_Background extends Mage_Adminhtml_Block_Widget_Grid_Container

{

    /**

     * constructor

     *

     * @access public

     * @return void

     * @author Ultimate Module Creator

     */

    public function __construct()

    {

        $this->_controller         = 'adminhtml_background';

        $this->_blockGroup         = 'vijay_custombackground';

        parent::__construct();

        $this->_headerText         = Mage::helper('vijay_custombackground')->__('Background');

        $this->_updateButton('add', 'label', Mage::helper('vijay_custombackground')->__('Add Background'));



    }

}

Step 8: Create file in app/code/community/Vijay/CustomBackground/Block/Adminhtml/Background/Grid.php and add below code in it.

<?php

class Vijay_CustomBackground_Block_Adminhtml_Background_Grid extends Mage_Adminhtml_Block_Widget_Grid
{
    /**
     * constructor
     *
     * @access public
     * @author Ultimate Module Creator
     */
    public function __construct()
    {
        parent::__construct();
        $this->setId('backgroundGrid');
        $this->setDefaultSort('entity_id');
        $this->setDefaultDir('ASC');
        $this->setSaveParametersInSession(true);
        $this->setUseAjax(true);
    }

    /**
     * prepare collection
     *
     * @access protected
     * @return Vijay_CustomBackground_Block_Adminhtml_Background_Grid
     * @author Ultimate Module Creator
     */
    protected function _prepareCollection()
    {
        $collection = Mage::getModel('vijay_custombackground/background')
            ->getCollection();
        
        $this->setCollection($collection);
        return parent::_prepareCollection();
    }

    /**
     * prepare grid collection
     *
     * @access protected
     * @return Vijay_CustomBackground_Block_Adminhtml_Background_Grid
     * @author Ultimate Module Creator
     */
    protected function _prepareColumns()
    {
        $this->addColumn(
            'entity_id',
            array(
                'header' => Mage::helper('vijay_custombackground')->__('Id'),
                'index'  => 'entity_id',
                'type'   => 'number'
            )
        );
        $this->addColumn(
            'background_name',
            array(
                'header'    => Mage::helper('vijay_custombackground')->__('Background Name'),
                'align'     => 'left',
                'index'     => 'background_name',
            )
        );
        
        $this->addColumn(
            'status',
            array(
                'header'  => Mage::helper('vijay_custombackground')->__('Status'),
                'index'   => 'status',
                'type'    => 'options',
                'options' => array(
                    '1' => Mage::helper('vijay_custombackground')->__('Enabled'),
                    '0' => Mage::helper('vijay_custombackground')->__('Disabled'),
                )
            )
        );
        $this->addColumn(
            'background_target',
            array(
                'header' => Mage::helper('vijay_custombackground')->__('Background Target'),
                'index'  => 'background_target',
                'type'  => 'options',
                'options' => Mage::helper('vijay_custombackground')->convertOptions(
                    Mage::getModel('vijay_custombackground/background_attribute_source_backgroundtarget')->getAllOptions(false)
                )

            )
        );
  $this->addColumn(
            'background_custom_target',
            array(
                'header' => Mage::helper('vijay_custombackground')->__('Custom CSS selector'),
                'index'  => 'background_custom_target',
                'type'=> 'text',

            )
        );
        $this->addColumn(
            'background_target_type',
            array(
                'header' => Mage::helper('vijay_custombackground')->__('Background Target Type'),
                'index'  => 'background_target_type',
                'type'  => 'options',
                'options' => Mage::helper('vijay_custombackground')->convertOptions(
                    Mage::getModel('vijay_custombackground/background_attribute_source_backgroundtargettype')->getAllOptions(false)
                )

            )
        );
  $this->addColumn(
            'background_target_id',
            array(
                'header' => Mage::helper('vijay_custombackground')->__('Background Target Page'),
                'index'  => 'background_target_id',
                'type'  => 'text',
                )
            );
  $this->addColumn(
            'background_target_id',
            array(
                'header' => Mage::helper('vijay_custombackground')->__('Background Target Page'),
                'index'  => 'background_target_id',
                'type'  => 'text',
                )
        );
        $this->addColumn(
            'background_category_id',
            array(
                'header' => Mage::helper('vijay_custombackground')->__('Background Target Category'),
                'index'  => 'background_category_id',
                'type'  => 'text',
                'renderer'  => 'Vijay_CustomBackground_Block_Adminhtml_Renderer_CategoryName',
                )
        );
  $this->addColumn(
            'background',
            array(
                'header' => Mage::helper('vijay_custombackground')->__('Background'),
             'align'     =>'left',
                'index'  => 'background',
                'type'=> 'text',
             'renderer'  => 'Vijay_CustomBackground_Block_Adminhtml_Renderer_Backgroundimg',

            )
        );
        /*$this->addColumn(
            'background_repeat',
            array(
                'header' => Mage::helper('vijay_custombackground')->__('Background Repeat'),
                'index'  => 'background_repeat',
                'type'=> 'text',

            )
        );
        $this->addColumn(
            'background_position',
            array(
                'header' => Mage::helper('vijay_custombackground')->__('Background Position'),
                'index'  => 'background_position',
                'type'=> 'text',

            )
        );
        $this->addColumn(
            'background_attachment',
            array(
                'header' => Mage::helper('vijay_custombackground')->__('Background Attachment'),
                'index'  => 'background_attachment',
                'type'=> 'text',

            )
        );
        $this->addColumn(
            'background_size',
            array(
                'header' => Mage::helper('vijay_custombackground')->__('Background Size'),
                'index'  => 'background_size',
                'type'=> 'text',

            )
        );
        $this->addColumn(
            'background_origin',
            array(
                'header' => Mage::helper('vijay_custombackground')->__('Background Origin'),
                'index'  => 'background_origin',
                'type'=> 'text',

            )
        );
        $this->addColumn(
            'background_clip',
            array(
                'header' => Mage::helper('vijay_custombackground')->__('Background Clip'),
                'index'  => 'background_clip',
                'type'=> 'text',

            )
        );
        $this->addColumn(
            'background_additional_style',
            array(
                'header' => Mage::helper('vijay_custombackground')->__('Background Additional Style'),
                'index'  => 'background_additional_style',
                'type'=> 'text',

            )
        );*/
        if (!Mage::app()->isSingleStoreMode() && !$this->_isExport) {
            $this->addColumn(
                'store_id',
                array(
                    'header'     => Mage::helper('vijay_custombackground')->__('Store Views'),
                    'index'      => 'store_id',
                    'type'       => 'store',
                    'store_all'  => true,
                    'store_view' => true,
                    'sortable'   => false,
                    'filter_condition_callback'=> array($this, '_filterStoreCondition'),
                )
            );
        }
        $this->addColumn(
            'created_at',
            array(
                'header' => Mage::helper('vijay_custombackground')->__('Created at'),
                'index'  => 'created_at',
                'width'  => '120px',
                'type'   => 'datetime',
            )
        );
        $this->addColumn(
            'updated_at',
            array(
                'header'    => Mage::helper('vijay_custombackground')->__('Updated at'),
                'index'     => 'updated_at',
                'width'     => '120px',
                'type'      => 'datetime',
            )
        );
        $this->addColumn(
            'action',
            array(
                'header'  =>  Mage::helper('vijay_custombackground')->__('Action'),
                'width'   => '100',
                'type'    => 'action',
                'getter'  => 'getId',
                'actions' => array(
                    array(
                        'caption' => Mage::helper('vijay_custombackground')->__('Edit'),
                        'url'     => array('base'=> '*/*/edit'),
                        'field'   => 'id'
                    )
                ),
                'filter'    => false,
                'is_system' => true,
                'sortable'  => false,
            )
        );
        $this->addExportType('*/*/exportCsv', Mage::helper('vijay_custombackground')->__('CSV'));
        $this->addExportType('*/*/exportExcel', Mage::helper('vijay_custombackground')->__('Excel'));
        $this->addExportType('*/*/exportXml', Mage::helper('vijay_custombackground')->__('XML'));
        return parent::_prepareColumns();
    }

    /**
     * prepare mass action
     *
     * @access protected
     * @return Vijay_CustomBackground_Block_Adminhtml_Background_Grid
     * @author Ultimate Module Creator
     */
    protected function _prepareMassaction()
    {
        $this->setMassactionIdField('entity_id');
        $this->getMassactionBlock()->setFormFieldName('background');
        $this->getMassactionBlock()->addItem(
            'delete',
            array(
                'label'=> Mage::helper('vijay_custombackground')->__('Delete'),
                'url'  => $this->getUrl('*/*/massDelete'),
                'confirm'  => Mage::helper('vijay_custombackground')->__('Are you sure?')
            )
        );
        $this->getMassactionBlock()->addItem(
            'status',
            array(
                'label'      => Mage::helper('vijay_custombackground')->__('Change status'),
                'url'        => $this->getUrl('*/*/massStatus', array('_current'=>true)),
                'additional' => array(
                    'status' => array(
                        'name'   => 'status',
                        'type'   => 'select',
                        'class'  => 'required-entry',
                        'label'  => Mage::helper('vijay_custombackground')->__('Status'),
                        'values' => array(
                            '1' => Mage::helper('vijay_custombackground')->__('Enabled'),
                            '0' => Mage::helper('vijay_custombackground')->__('Disabled'),
                        )
                    )
                )
            )
        );
        $this->getMassactionBlock()->addItem(
            'background_target',
            array(
                'label'      => Mage::helper('vijay_custombackground')->__('Change Background Target'),
                'url'        => $this->getUrl('*/*/massBackgroundTarget', array('_current'=>true)),
                'additional' => array(
                    'flag_background_target' => array(
                        'name'   => 'flag_background_target',
                        'type'   => 'select',
                        'class'  => 'required-entry',
                        'label'  => Mage::helper('vijay_custombackground')->__('Background Target'),
                        'values' => Mage::getModel('vijay_custombackground/background_attribute_source_backgroundtarget')
                            ->getAllOptions(true),

                    )
                )
            )
        );
        $this->getMassactionBlock()->addItem(
            'background_target_type',
            array(
                'label'      => Mage::helper('vijay_custombackground')->__('Change Background Target Type'),
                'url'        => $this->getUrl('*/*/massBackgroundTargetType', array('_current'=>true)),
                'additional' => array(
                    'flag_background_target_type' => array(
                        'name'   => 'flag_background_target_type',
                        'type'   => 'select',
                        'class'  => 'required-entry',
                        'label'  => Mage::helper('vijay_custombackground')->__('Background Target Type'),
                        'values' => Mage::getModel('vijay_custombackground/background_attribute_source_backgroundtargettype')
                            ->getAllOptions(true),

                    )
                )
            )
        );
        return $this;
    }

    /**
     * get the row url
     *
     * @access public
     * @param Vijay_CustomBackground_Model_Background
     * @return string
     * @author Ultimate Module Creator
     */
    public function getRowUrl($row)
    {
        return $this->getUrl('*/*/edit', array('id' => $row->getId()));
    }

    /**
     * get the grid url
     *
     * @access public
     * @return string
     * @author Ultimate Module Creator
     */
    public function getGridUrl()
    {
        return $this->getUrl('*/*/grid', array('_current'=>true));
    }

    /**
     * after collection load
     *
     * @access protected
     * @return Vijay_CustomBackground_Block_Adminhtml_Background_Grid
     * @author Ultimate Module Creator
     */
    protected function _afterLoadCollection()
    {
        $this->getCollection()->walk('afterLoad');
        parent::_afterLoadCollection();
    }

    /**
     * filter store column
     *
     * @access protected
     * @param Vijay_CustomBackground_Model_Resource_Background_Collection $collection
     * @param Mage_Adminhtml_Block_Widget_Grid_Column $column
     * @return Vijay_CustomBackground_Block_Adminhtml_Background_Grid
     * @author Ultimate Module Creator
     */
    protected function _filterStoreCondition($collection, $column)
    {
        if (!$value = $column->getFilter()->getValue()) {
            return;
        }
        $collection->addStoreFilter($value);
        return $this;
    }
}

Step 9: Create file in app/code/community/Vijay/CustomBackground/Block/Adminhtml/Background/Edit.php and add below code in it.

<?php

class Vijay_CustomBackground_Block_Adminhtml_Background_Edit extends Mage_Adminhtml_Block_Widget_Form_Container
{
    /**
     * constructor
     *
     * @access public
     * @return void
     * @author Ultimate Module Creator
     */
    public function __construct()
    {
        parent::__construct();
        $this->_blockGroup = 'vijay_custombackground';
        $this->_controller = 'adminhtml_background';
        $this->_updateButton(
            'save',
            'label',
            Mage::helper('vijay_custombackground')->__('Save Background')
        );
        $this->_updateButton(
            'delete',
            'label',
            Mage::helper('vijay_custombackground')->__('Delete Background')
        );
        $this->_addButton(
            'saveandcontinue',
            array(
                'label'   => Mage::helper('vijay_custombackground')->__('Save And Continue Edit'),
                'onclick' => 'saveAndContinueEdit()',
                'class'   => 'save',
            ),
            -100
        );
        $this->_formScripts[] = "
            function saveAndContinueEdit() {
                editForm.submit($('edit_form').action+'back/edit/');
            }
        ";
    }
    /**
     * get the edit form header
     *
     * @access public
     * @return string
     * @author Ultimate Module Creator
     */
    public function getHeaderText()
    {
        if (Mage::registry('current_background') && Mage::registry('current_background')->getId()) {
            return Mage::helper('vijay_custombackground')->__(
                "Edit Background '%s'",
                $this->escapeHtml(Mage::registry('current_background')->getBackgroundName())
            );
        } else {
            return Mage::helper('vijay_custombackground')->__('Add Background');
        }
    }
}

Step 10: Create file in app/code/community/Vijay/CustomBackground/Block/Adminhtml/Background/Helper/Image.php and add below code in it.

<?php

class Vijay_CustomBackground_Block_Adminhtml_Background_Helper_Image extends Varien_Data_Form_Element_Image
{
    /**
     * get the url of the image
     *
     * @access protected
     * @return string
     * @author Ultimate Module Creator
     */
    protected function _getUrl()
    {
        $url = false;
        if ($this->getValue()) {
            $url = Mage::helper('vijay_custombackground/background_image')->getImageBaseUrl().
                $this->getValue();
        }
        return $url;
    }
}

Step 11: Create file in app/code/community/Vijay/CustomBackground/Block/Adminhtml/Background/Edit/Tabs.php and add below code in it.

<?php

class Vijay_CustomBackground_Block_Adminhtml_Background_Edit_Tabs extends Mage_Adminhtml_Block_Widget_Tabs
{
    /**
     * Initialize Tabs
     *
     * @access public
     * @author Ultimate Module Creator
     */
    public function __construct()
    {
        parent::__construct();
        $this->setId('background_tabs');
        $this->setDestElementId('edit_form');
        $this->setTitle(Mage::helper('vijay_custombackground')->__('Background'));
    }

    /**
     * before render html
     *
     * @access protected
     * @return Vijay_CustomBackground_Block_Adminhtml_Background_Edit_Tabs
     * @author Ultimate Module Creator
     */
    protected function _beforeToHtml()
    {
        $this->addTab(
            'form_background',
            array(
                'label'   => Mage::helper('vijay_custombackground')->__('Background'),
                'title'   => Mage::helper('vijay_custombackground')->__('Background'),
                'content' => $this->getLayout()->createBlock(
                    'vijay_custombackground/adminhtml_background_edit_tab_form'
                )
                ->toHtml(),
            )
        );
        if (!Mage::app()->isSingleStoreMode()) {
            $this->addTab(
                'form_store_background',
                array(
                    'label'   => Mage::helper('vijay_custombackground')->__('Store views'),
                    'title'   => Mage::helper('vijay_custombackground')->__('Store views'),
                    'content' => $this->getLayout()->createBlock(
                        'vijay_custombackground/adminhtml_background_edit_tab_stores'
                    )
                    ->toHtml(),
                )
            );
        }
        return parent::_beforeToHtml();
    }

    /**
     * Retrieve background entity
     *
     * @access public
     * @return Vijay_CustomBackground_Model_Background
     * @author Ultimate Module Creator
     */
    public function getBackground()
    {
        return Mage::registry('current_background');
    }
}

Step 12: Create file in app/code/community/Vijay/CustomBackground/Block/Adminhtml/Background/Edit/Form.php and add below code in it.

<?php

class Vijay_CustomBackground_Block_Adminhtml_Background_Edit_Form extends Mage_Adminhtml_Block_Widget_Form
{
    /**
     * prepare form
     *
     * @access protected
     * @return Vijay_CustomBackground_Block_Adminhtml_Background_Edit_Form
     * @author Ultimate Module Creator
     */
    protected function _prepareForm()
    {
        $form = new Varien_Data_Form(
            array(
                'id'         => 'edit_form',
                'action'     => $this->getUrl(
                    '*/*/save',
                    array(
                        'id' => $this->getRequest()->getParam('id')
                    )
                ),
                'method'     => 'post',
                'enctype'    => 'multipart/form-data'
            )
        );
        $form->setUseContainer(true);
        $this->setForm($form);
        return parent::_prepareForm();
    }
}

Step 13: Create file in app/code/community/Vijay/CustomBackground/Block/Adminhtml/Background/Edit/Tab/Form.php and add below code in it.

<?php

class Vijay_CustomBackground_Block_Adminhtml_Background_Edit_Tab_Form extends Mage_Adminhtml_Block_Widget_Form
{
    /**
     * prepare the form
     *
     * @access protected
     * @return Vijay_CustomBackground_Block_Adminhtml_Background_Edit_Tab_Form
     * @author Ultimate Module Creator
     */
    protected function _prepareForm()
    {
        $form = new Varien_Data_Form();
        $form->setHtmlIdPrefix('background_');
        $form->setFieldNameSuffix('background');
        $this->setForm($form);
        $fieldset = $form->addFieldset(
            'background_form',
            array('legend' => Mage::helper('vijay_custombackground')->__('Background'))
        );
        $fieldset->addType(
            'image',
            Mage::getConfig()->getBlockClassName('vijay_custombackground/adminhtml_background_helper_image')
        );

        $fieldset->addField(
            'background_name',
            'text',
            array(
                'label' => Mage::helper('vijay_custombackground')->__('Background Name'),
                'name'  => 'background_name',
                'required'  => true,
                'class' => 'required-entry',

           )
        );

        $customtypefield = $fieldset->addField(
            'background_target',
            'select',
            array(
                'label' => Mage::helper('vijay_custombackground')->__('Background Target'),
                'name'  => 'background_target',
                'required'  => true,
                'class' => 'required-entry',

                'values'=> Mage::getModel('vijay_custombackground/background_attribute_source_backgroundtarget')->getAllOptions(true),
                'onchange' => 'onchangeCustomStyleShow(this.value)',
           )
        );
  
  $customtypefield->setAfterElementHtml("");
  
  $fieldset->addField(
            'background_custom_target',
            'text',
            array(
                'label' => Mage::helper('vijay_custombackground')->__('Custom CSS selector'),
                'name'  => 'background_custom_target',
                'required'  => false,
                'note'=>'Input CSS selector, like .class or #id',
           )
        );
   
        $typefield = $fieldset->addField(
            'background_target_type',
            'select',
            array(
                'label' => Mage::helper('vijay_custombackground')->__('Background Target Type'),
                'name'  => 'background_target_type',
                'required'  => true,
                'class' => 'required-entry',

                'values'=> Mage::getModel('vijay_custombackground/background_attribute_source_backgroundtargettype')->getAllOptions(true),
                'onchange' => 'onchangeStyleShow(this.value)',
           )
           
        );
  
  $typefield->setAfterElementHtml("");
  
      
  $options = $collection = Mage::getModel('cms/page')
                    ->getCollection()
                    ->addFieldToFilter('identifier',
      array(
                          array('neq' => 'home'),// add your custome identifier name for home page
                     )
     )
     ->addFieldToFilter('is_active',1)
                    ->toOptionArray();
     
        $fieldset->addField(
            'background_target_id',
            'multiselect',
            array(
                'label' => Mage::helper('vijay_custombackground')->__('Background Target Page'),
                'name'  => 'background_target_id',
                'values'=> $options,
           )
        );
  
  $fieldset->addField(
            'background_category_id',
            'multiselect',
            array(
                'label' => Mage::helper('vijay_custombackground')->__('Background Target Category'),
                'name'  => 'background_category_id',
                'values'   => Mage::getModel('vijay_custombackground/background_attribute_source_productcategories')->getOptionArray(),
           )
        );

        $fieldset->addField(
            'background',
            'image',
            array(
                'label' => Mage::helper('vijay_custombackground')->__('Background'),
                'name'  => 'background',
                'required'  => true,
                'class' => 'required-entry required-file',

           )
        )->setAfterElementHtml("");;
  
  $this->setChild(
  'form_after', 
  $this->getLayout()
         ->createBlock('adminhtml/widget_form_element_dependence')
         ->addFieldMap('background_background_target_type', 'background_target_type')
         ->addFieldMap('background_background_target_id', 'background_target_id')
         ->addFieldDependence('background_target_id', 'background_target_type', 1)
   ->addFieldMap('background_background_target_type', 'background_target_type')
         ->addFieldMap('background_background_category_id', 'background_category_id')
         ->addFieldDependence('background_category_id', 'background_target_type', 3)
   ->addFieldMap('background_background_target', 'background_background_target')
         ->addFieldMap('background_background_custom_target', 'background_background_custom_target')
         ->addFieldDependence('background_background_custom_target', 'background_background_target', 'custom')
  );
        $fieldset->addField(
            'background_color',
            'text',
            array(
                'label' => Mage::helper('vijay_custombackground')->__('Background Color'),
                'name'  => 'background_color',
                'class' => 'color {required:true, adjust:true, hash:true} validate-hex'

           )
        );

        $fieldset->addField(
            'background_repeat',
            'select',
            array(
                'label' => Mage::helper('vijay_custombackground')->__('Background Repeat'),
                'name'  => 'background_repeat',
                'values'=> Mage::getModel('vijay_custombackground/background_attribute_source_backgroundrepeat')->getAllOptions(true),

           )
        );

        $fieldset->addField(
            'background_position',
            'select',
            array(
                'label' => Mage::helper('vijay_custombackground')->__('Background Position'),
                'name'  => 'background_position',
                'values'=> Mage::getModel('vijay_custombackground/background_attribute_source_backgroundposition')->getAllOptions(true),

           )
        );

        $fieldset->addField(
            'background_attachment',
            'select',
            array(
                'label' => Mage::helper('vijay_custombackground')->__('Background Attachment'),
                'name'  => 'background_attachment',
                'values'=> Mage::getModel('vijay_custombackground/background_attribute_source_backgroundattachment')->getAllOptions(true),

           )
        );

        $fieldset->addField(
            'background_size',
            'select',
            array(
                'label' => Mage::helper('vijay_custombackground')->__('Background Size'),
                'name'  => 'background_size',
                'values'=> Mage::getModel('vijay_custombackground/background_attribute_source_backgroundsize')->getAllOptions(true),

           )
        );

        $fieldset->addField(
            'background_origin',
            'select',
            array(
                'label' => Mage::helper('vijay_custombackground')->__('Background Origin'),
                'name'  => 'background_origin',
                'values'=> Mage::getModel('vijay_custombackground/background_attribute_source_backgroundorigin')->getAllOptions(true),

           )
        );

        $fieldset->addField(
            'background_clip',
            'select',
            array(
                'label' => Mage::helper('vijay_custombackground')->__('Background Clip'),
                'name'  => 'background_clip',
    'values'=> Mage::getModel('vijay_custombackground/background_attribute_source_backgroundclip')->getAllOptions(true),
           )
        );

        $fieldset->addField(
            'background_additional_style',
            'text',
            array(
                'label' => Mage::helper('vijay_custombackground')->__('Background Additional Style'),
                'name'  => 'background_additional_style',

           )
        );
        $fieldset->addField(
            'status',
            'select',
            array(
                'label'  => Mage::helper('vijay_custombackground')->__('Status'),
                'name'   => 'status',
                'values' => array(
                    array(
                        'value' => 1,
                        'label' => Mage::helper('vijay_custombackground')->__('Enabled'),
                    ),
                    array(
                        'value' => 0,
                        'label' => Mage::helper('vijay_custombackground')->__('Disabled'),
                    ),
                ),
            )
        );
        if (Mage::app()->isSingleStoreMode()) {
            $fieldset->addField(
                'store_id',
                'hidden',
                array(
                    'name'      => 'stores[]',
                    'value'     => Mage::app()->getStore(true)->getId()
                )
            );
            Mage::registry('current_background')->setStoreId(Mage::app()->getStore(true)->getId());
        }
        $formValues = Mage::registry('current_background')->getDefaultValues();
        if (!is_array($formValues)) {
            $formValues = array();
        }
        if (Mage::getSingleton('adminhtml/session')->getBackgroundData()) {
            $formValues = array_merge($formValues, Mage::getSingleton('adminhtml/session')->getBackgroundData());
            Mage::getSingleton('adminhtml/session')->setBackgroundData(null);
        } elseif (Mage::registry('current_background')) {
            $formValues = array_merge($formValues, Mage::registry('current_background')->getData());
        }
        $form->setValues($formValues);
        return parent::_prepareForm();
    }
}

Step 14: Create file in app/code/community/Vijay/CustomBackground/Block/Adminhtml/Background/Edit/Tab/Stores.php and add below code in it.

<?php

class Vijay_CustomBackground_Block_Adminhtml_Background_Edit_Tab_Stores extends Mage_Adminhtml_Block_Widget_Form
{
    /**
     * prepare the form
     *
     * @access protected
     * @return Vijay_CustomBackground_Block_Adminhtml_Background_Edit_Tab_Stores
     * @author Ultimate Module Creator
     */
    protected function _prepareForm()
    {
        $form = new Varien_Data_Form();
        $form->setFieldNameSuffix('background');
        $this->setForm($form);
        $fieldset = $form->addFieldset(
            'background_stores_form',
            array('legend' => Mage::helper('vijay_custombackground')->__('Store views'))
        );
        $field = $fieldset->addField(
            'store_id',
            'multiselect',
            array(
                'name'     => 'stores[]',
                'label'    => Mage::helper('vijay_custombackground')->__('Store Views'),
                'title'    => Mage::helper('vijay_custombackground')->__('Store Views'),
                'required' => true,
                'values'   => Mage::getSingleton('adminhtml/system_store')->getStoreValuesForForm(false, true),
            )
        );
        $renderer = $this->getLayout()->createBlock('adminhtml/store_switcher_form_renderer_fieldset_element');
        $field->setRenderer($renderer);
        $form->addValues(Mage::registry('current_background')->getData());
        return parent::_prepareForm();
    }
}

Step 15: Create file in app/code/community/Vijay/CustomBackground/Block/Adminhtml/Renderer/Backgroundimg.php and add below code in it.

<?php

class Vijay_CustomBackground_Block_Adminhtml_Renderer_Backgroundimg extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
{ 
 public function render(Varien_Object $row) 
 {
  $data =  $row->getData($this->getColumn()->getIndex());
  $id=$row->getData();
  if(isset($id['background']) && $id['background'] != '')
  {
     $value='
Show Photo
'; return $value; } } }

Step 16: Create file in app/code/community/Vijay/CustomBackground/Block/Adminhtml/Renderer/CategoryName.php and add below code in it.

<?php

class Vijay_CustomBackground_Block_Adminhtml_Renderer_CategoryName extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
{
        public function render(Varien_Object $row) 
 {
         $data =  $row->getData($this->getColumn()->getIndex());
         $id=$row->getData();
         
         if(isset($id['background_category_id']) && $id['background_category_id'] != '')
         {
                 $categoryids = $id['background_category_id'];   
     $categoryarray = explode(",",$id['background_category_id']);
     foreach ($categoryarray as $category_id) {
        $_cat = Mage::getModel('catalog/category')->setStoreId(Mage::app()->getStore()->getId())->load($category_id);
           $categoryname .= $_cat->getName()." , ";             
        }
    return rtrim($categoryname,' , ');
         }
         
 }
}

Step 17: Create file in app/code/community/Vijay/CustomBackground/Controller/Adminhtml/CustomBackground.php and add below code in it.

<?php

class Vijay_CustomBackground_Controller_Adminhtml_CustomBackground extends Mage_Adminhtml_Controller_Action
{
    /**
     * upload file and get the uploaded name
     *
     * @access public
     * @param string $input
     * @param string $destinationFolder
     * @param array $data
     * @return string
     * @author Ultimate Module Creator
     */
    protected function _uploadAndGetName($input, $destinationFolder, $data)
    {
        try {
            if (isset($data[$input]['delete'])) {
                return '';
            } else {
                $uploader = new Varien_File_Uploader($input);
    $uploader->setAllowedExtensions(array('jpg', 'jpeg', 'gif', 'png'));
                $uploader->setAllowRenameFiles(true);
                $uploader->setFilesDispersion(true);
                $uploader->setAllowCreateFolders(true);
                $result = $uploader->save($destinationFolder);
                return $result['file'];
            }
        } catch (Exception $e) {
            if ($e->getCode() != Varien_File_Uploader::TMP_NAME_EMPTY) {
                throw $e;
            } else {
                if (isset($data[$input]['value'])) {
                    return $data[$input]['value'];
                }
            }
        }
        return '';
    }
}

Step 18: Create file in app/code/community/Vijay/CustomBackground/controllers/Adminhtml/Custombackground/BackgroundController.php and add below code in it.

<?php

class Vijay_CustomBackground_Adminhtml_Custombackground_BackgroundController extends Vijay_CustomBackground_Controller_Adminhtml_CustomBackground
{
    /**
     * init the background
     *
     * @access protected
     * @return Vijay_CustomBackground_Model_Background
     */
    protected function _initBackground()
    {
        $backgroundId  = (int) $this->getRequest()->getParam('id');
        $background    = Mage::getModel('vijay_custombackground/background');
        if ($backgroundId) {
            $background->load($backgroundId);
        }
        Mage::register('current_background', $background);
        return $background;
    }

    /**
     * default action
     *
     * @access public
     * @return void
     * @author Ultimate Module Creator
     */
    public function indexAction()
    {
        $this->loadLayout();
        $this->_title(Mage::helper('vijay_custombackground')->__('Custom Background'))
             ->_title(Mage::helper('vijay_custombackground')->__('Backgrounds'));
        $this->renderLayout();
    }

    /**
     * grid action
     *
     * @access public
     * @return void
     * @author Ultimate Module Creator
     */
    public function gridAction()
    {
        $this->loadLayout()->renderLayout();
    }

    /**
     * edit background - action
     *
     * @access public
     * @return void
     * @author Ultimate Module Creator
     */
    public function editAction()
    {
        $backgroundId    = $this->getRequest()->getParam('id');
        $background      = $this->_initBackground();
        if ($backgroundId && !$background->getId()) {
            $this->_getSession()->addError(
                Mage::helper('vijay_custombackground')->__('This background no longer exists.')
            );
            $this->_redirect('*/*/');
            return;
        }
        $data = Mage::getSingleton('adminhtml/session')->getBackgroundData(true);
        if (!empty($data)) {
            $background->setData($data);
        }
        Mage::register('background_data', $background);
        $this->loadLayout();
        $this->_title(Mage::helper('vijay_custombackground')->__('Custom Background'))
             ->_title(Mage::helper('vijay_custombackground')->__('Backgrounds'));
        if ($background->getId()) {
            $this->_title($background->getBackgroundName());
        } else {
            $this->_title(Mage::helper('vijay_custombackground')->__('Add background'));
        }
        if (Mage::getSingleton('cms/wysiwyg_config')->isEnabled()) {
            $this->getLayout()->getBlock('head')->setCanLoadTinyMce(true);
        }
        $this->renderLayout();
    }

    /**
     * new background action
     *
     * @access public
     * @return void
     * @author Ultimate Module Creator
     */
    public function newAction()
    {
        $this->_forward('edit');
    }

    /**
     * save background - action
     *
     * @access public
     * @return void
     * @author Ultimate Module Creator
     */
    public function saveAction()
    {
        if ($data = $this->getRequest()->getPost('background')) {
            try {
                $background = $this->_initBackground();
                $background->addData($data);
                $backgroundName = $this->_uploadAndGetName(
                    'background',
                    Mage::helper('vijay_custombackground/background_image')->getImageBaseDir(),
                    $data
                );
    /* Custom code start */
    if(isset($data['background_target']) && $data['background_target'] != 'custom'){
     $backgroundCustomTarget = NULL;
     $background->setData('background_custom_target', $backgroundCustomTarget);
    }
    if(isset($data['background_category_id']) && is_array($data['background_category_id'])){
     $backgroundCategoryTarget = implode(",",$data['background_category_id']);
     $background->setData('background_category_id', $backgroundCategoryTarget);
    }
    if(isset($data['background_target_type']) && ($data['background_target_type'] == '3')){
     $backgroundTargetId = NULL;
     $background->setData('background_target_id', $backgroundTargetId);
    }
    if(isset($data['background_target_type']) && ($data['background_target_type'] == '1')){
     $backgroundCategoryId = NULL;
     $background->setData('background_category_id', $backgroundCategoryId);
    }
    /* Custom code Ends */
                $background->setData('background', $backgroundName);
                $background->save();
                Mage::getSingleton('adminhtml/session')->addSuccess(
                    Mage::helper('vijay_custombackground')->__('Background was successfully saved')
                );
                Mage::getSingleton('adminhtml/session')->setFormData(false);
                if ($this->getRequest()->getParam('back')) {
                    $this->_redirect('*/*/edit', array('id' => $background->getId()));
                    return;
                }
                $this->_redirect('*/*/');
                return;
            } catch (Mage_Core_Exception $e) {
                if (isset($data['background']['value'])) {
                    $data['background'] = $data['background']['value'];
                }
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
                Mage::getSingleton('adminhtml/session')->setBackgroundData($data);
                $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
                return;
            } catch (Exception $e) {
                Mage::logException($e);
                if (isset($data['background']['value'])) {
                    $data['background'] = $data['background']['value'];
                }
                Mage::getSingleton('adminhtml/session')->addError(
                    Mage::helper('vijay_custombackground')->__('There was a problem saving the background.')
                );
                Mage::getSingleton('adminhtml/session')->setBackgroundData($data);
                $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
                return;
            }
        }
        Mage::getSingleton('adminhtml/session')->addError(
            Mage::helper('vijay_custombackground')->__('Unable to find background to save.')
        );
        $this->_redirect('*/*/');
    }

    /**
     * delete background - action
     *
     * @access public
     * @return void
     * @author Ultimate Module Creator
     */
    public function deleteAction()
    {
        if ( $this->getRequest()->getParam('id') > 0) {
            try {
                $background = Mage::getModel('vijay_custombackground/background');
                $background->setId($this->getRequest()->getParam('id'))->delete();
                Mage::getSingleton('adminhtml/session')->addSuccess(
                    Mage::helper('vijay_custombackground')->__('Background was successfully deleted.')
                );
                $this->_redirect('*/*/');
                return;
            } catch (Mage_Core_Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
                $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
            } catch (Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError(
                    Mage::helper('vijay_custombackground')->__('There was an error deleting background.')
                );
                $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
                Mage::logException($e);
                return;
            }
        }
        Mage::getSingleton('adminhtml/session')->addError(
            Mage::helper('vijay_custombackground')->__('Could not find background to delete.')
        );
        $this->_redirect('*/*/');
    }

    /**
     * mass delete background - action
     *
     * @access public
     * @return void
     * @author Ultimate Module Creator
     */
    public function massDeleteAction()
    {
        $backgroundIds = $this->getRequest()->getParam('background');
        if (!is_array($backgroundIds)) {
            Mage::getSingleton('adminhtml/session')->addError(
                Mage::helper('vijay_custombackground')->__('Please select backgrounds to delete.')
            );
        } else {
            try {
                foreach ($backgroundIds as $backgroundId) {
                    $background = Mage::getModel('vijay_custombackground/background');
                    $background->setId($backgroundId)->delete();
                }
                Mage::getSingleton('adminhtml/session')->addSuccess(
                    Mage::helper('vijay_custombackground')->__('Total of %d backgrounds were successfully deleted.', count($backgroundIds))
                );
            } catch (Mage_Core_Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
            } catch (Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError(
                    Mage::helper('vijay_custombackground')->__('There was an error deleting backgrounds.')
                );
                Mage::logException($e);
            }
        }
        $this->_redirect('*/*/index');
    }

    /**
     * mass status change - action
     *
     * @access public
     * @return void
     * @author Ultimate Module Creator
     */
    public function massStatusAction()
    {
        $backgroundIds = $this->getRequest()->getParam('background');
        if (!is_array($backgroundIds)) {
            Mage::getSingleton('adminhtml/session')->addError(
                Mage::helper('vijay_custombackground')->__('Please select backgrounds.')
            );
        } else {
            try {
                foreach ($backgroundIds as $backgroundId) {
                $background = Mage::getSingleton('vijay_custombackground/background')->load($backgroundId)
                            ->setStatus($this->getRequest()->getParam('status'))
                            ->setIsMassupdate(true)
                            ->save();
                }
                $this->_getSession()->addSuccess(
                    $this->__('Total of %d backgrounds were successfully updated.', count($backgroundIds))
                );
            } catch (Mage_Core_Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
            } catch (Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError(
                    Mage::helper('vijay_custombackground')->__('There was an error updating backgrounds.')
                );
                Mage::logException($e);
            }
        }
        $this->_redirect('*/*/index');
    }

    /**
     * mass Background Target change - action
     *
     * @access public
     * @return void
     * @author Ultimate Module Creator
     */
    public function massBackgroundTargetAction()
    {
        $backgroundIds = $this->getRequest()->getParam('background');
        if (!is_array($backgroundIds)) {
            Mage::getSingleton('adminhtml/session')->addError(
                Mage::helper('vijay_custombackground')->__('Please select backgrounds.')
            );
        } else {
            try {
                foreach ($backgroundIds as $backgroundId) {
                $background = Mage::getSingleton('vijay_custombackground/background')->load($backgroundId)
                    ->setBackgroundTarget($this->getRequest()->getParam('flag_background_target'))
                    ->setIsMassupdate(true)
                    ->save();
                }
                $this->_getSession()->addSuccess(
                    $this->__('Total of %d backgrounds were successfully updated.', count($backgroundIds))
                );
            } catch (Mage_Core_Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
            } catch (Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError(
                    Mage::helper('vijay_custombackground')->__('There was an error updating backgrounds.')
                );
                Mage::logException($e);
            }
        }
        $this->_redirect('*/*/index');
    }

    /**
     * mass Background Target Type change - action
     *
     * @access public
     * @return void
     * @author Ultimate Module Creator
     */
    public function massBackgroundTargetTypeAction()
    {
        $backgroundIds = $this->getRequest()->getParam('background');
        if (!is_array($backgroundIds)) {
            Mage::getSingleton('adminhtml/session')->addError(
                Mage::helper('vijay_custombackground')->__('Please select backgrounds.')
            );
        } else {
            try {
                foreach ($backgroundIds as $backgroundId) {
                $background = Mage::getSingleton('vijay_custombackground/background')->load($backgroundId)
                    ->setBackgroundTargetType($this->getRequest()->getParam('flag_background_target_type'))
                    ->setIsMassupdate(true)
                    ->save();
                }
                $this->_getSession()->addSuccess(
                    $this->__('Total of %d backgrounds were successfully updated.', count($backgroundIds))
                );
            } catch (Mage_Core_Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
            } catch (Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError(
                    Mage::helper('vijay_custombackground')->__('There was an error updating backgrounds.')
                );
                Mage::logException($e);
            }
        }
        $this->_redirect('*/*/index');
    }

    /**
     * export as csv - action
     *
     * @access public
     * @return void
     * @author Ultimate Module Creator
     */
    public function exportCsvAction()
    {
        $fileName   = 'background.csv';
        $content    = $this->getLayout()->createBlock('vijay_custombackground/adminhtml_background_grid')
            ->getCsv();
        $this->_prepareDownloadResponse($fileName, $content);
    }

    /**
     * export as MsExcel - action
     *
     * @access public
     * @return void
     * @author Ultimate Module Creator
     */
    public function exportExcelAction()
    {
        $fileName   = 'background.xls';
        $content    = $this->getLayout()->createBlock('vijay_custombackground/adminhtml_background_grid')
            ->getExcelFile();
        $this->_prepareDownloadResponse($fileName, $content);
    }

    /**
     * export as xml - action
     *
     * @access public
     * @return void
     * @author Ultimate Module Creator
     */
    public function exportXmlAction()
    {
        $fileName   = 'background.xml';
        $content    = $this->getLayout()->createBlock('vijay_custombackground/adminhtml_background_grid')
            ->getXml();
        $this->_prepareDownloadResponse($fileName, $content);
    }

    /**
     * Check if admin has permissions to visit related pages
     *
     * @access protected
     * @return boolean
     * @author Ultimate Module Creator
     */
    protected function _isAllowed()
    {
        return Mage::getSingleton('admin/session')->isAllowed('vijay_custombackground/background');
    }
}

Step 19: Create file in app/code/community/Vijay/CustomBackground/Helper/Data.php and add below code in it.

<?php

class Vijay_CustomBackground_Helper_Data extends Mage_Core_Helper_Abstract
{
    /**
     * convert array to options
     *
     * @access public
     * @param $options
     * @return array
     * @author Ultimate Module Creator
     */
    public function convertOptions($options)
    {
        $converted = array();
        foreach ($options as $option) {
            if (isset($option['value']) && !is_array($option['value']) &&
                isset($option['label']) && !is_array($option['label'])) {
                $converted[$option['value']] = $option['label'];
            }
        }
        return $converted;
    }
 public function getCurrentBackground()
    {
     if ($this->getPageHelper()->isHomePage()) {
            $background = Mage::getModel('vijay_custombackground/background')
                        ->getCollection()
                        ->addStoreFilter(Mage::app()->getStore())
                        ->addFieldToFilter('status',1)
                        ->addFieldToFilter('background_target_type',Vijay_CustomBackground_Model_Background::TARGET_HOME)
                        ->getFirstItem();
        }
  if ($this->getPageHelper()->isCmsPage() && !$this->getPageHelper()->isHomePage()) {
            $background = Mage::getModel('vijay_custombackground/background')
                        ->getCollection()
                        ->addFieldToFilter('status',1)
                        ->addStoreFilter(Mage::app()->getStore())
                        ->addFieldToFilter('background_target_type',Vijay_CustomBackground_Model_Background::TARGET_CMS)
                        ->addFieldToFilter('background_target_id',array('regexp'=>'(^|,)'.Mage::getSingleton('cms/page')->getIdentifier().'(,|$)'))
                        ->getFirstItem();
      
        }
  if ($this->getPageHelper()->isCategoryPage()) {
            $background = Mage::getModel('vijay_custombackground/background')
                        ->getCollection()
                        ->addStoreFilter(Mage::app()->getStore())
                        ->addFieldToFilter('status',1)
                        ->addFieldToFilter('background_target_type',Vijay_CustomBackground_Model_Background::TARGET_CATEGORY)
                        ->getFirstItem();
   $backgroundCategories = $background->getBackgroundCategoryId();
   $bgarray = explode(",",$backgroundCategories);
 
   $curcategoryId = $this->getPageHelper()->getCurrentCategoryId();
   if (!in_array($curcategoryId, $bgarray)){
    $background = '';
   }
   
        }
  if ($this->getPageHelper()->isProductPage()) {
            $background = Mage::getModel('vijay_custombackground/background')
                        ->getCollection()
                        ->addStoreFilter(Mage::app()->getStore())
                        ->addFieldToFilter('status',1)
                        ->addFieldToFilter('background_target_type',Vijay_CustomBackground_Model_Background::TARGET_PRODUCT)
                        ->getFirstItem();
        }
  if ($this->getPageHelper()->isCheckoutPage()) {
            $background = Mage::getModel('vijay_custombackground/background')
                        ->getCollection()
                        ->addStoreFilter(Mage::app()->getStore())
                        ->addFieldToFilter('status',1)
                        ->addFieldToFilter('background_target_type',Vijay_CustomBackground_Model_Background::TARGET_CHECKOUT)
                        ->getFirstItem();
        }
        if ($this->getPageHelper()->isCartPage()) {
            $background = Mage::getModel('vijay_custombackground/background')
                        ->getCollection()
                        ->addStoreFilter(Mage::app()->getStore())
                        ->addFieldToFilter('status',1)
                        ->addFieldToFilter('background_target_type',Vijay_CustomBackground_Model_Background::TARGET_CART)
                        ->getFirstItem();
        }
  if ($this->getPageHelper()->isAccountPage()) {
            $background = Mage::getModel('vijay_custombackground/background')
                        ->getCollection()
                        ->addStoreFilter(Mage::app()->getStore())
                        ->addFieldToFilter('status',1)
                        ->addFieldToFilter('background_target_type',Vijay_CustomBackground_Model_Background::TARGET_CUSTOMER)
                        ->getFirstItem();
        }
  if ($this->getPageHelper()->isOtherPage()) {
            $background = Mage::getModel('vijay_custombackground/background')
                        ->getCollection()
                        ->addStoreFilter(Mage::app()->getStore())
                        ->addFieldToFilter('status',1)
                        ->addFieldToFilter('background_target_type',Vijay_CustomBackground_Model_Background::TARGET_OTHER)
                        ->getFirstItem();
        }
  
  return $background;
    }
 /**
     * @return Vijay_CustomBackground_Helper_Page
     */
    public function getPageHelper()
    {
        return Mage::helper('vijay_custombackground/page');
    }
}

Step 20: Create file in app/code/community/Vijay/CustomBackground/Helper/Page.php and add below code in it.

<?php

class Vijay_CustomBackground_Helper_Page extends Mage_Core_Helper_Data
{
    public function isHomePage()
    {
        $currentUrl = Mage::getUrl('*/*/*', array('_current' => true, '_use_rewrite' => true));
        $homePageUrl = Mage::getUrl('');
        return $currentUrl === $homePageUrl;
    }
    public function isProductPage()
    {
        $allowedActionNameList = array(
            'catalog_product_view',
        );
        $product = Mage::registry('current_product');
        return in_array(Mage::app()->getFrontController()->getAction()->getFullActionName(), $allowedActionNameList) && $product && $product->getId();
    }
    public function isCmsPage()
    {
        $page = Mage::getSingleton('cms/page');
        return $page->getId();
    }
    public function isCategoryPage()
    {
        $allowedActionNameList = array(
            'catalog_category_default',
            'catalog_category_layered',
            'catalog_category_view',
        );
        $category = Mage::registry('current_category');
        return in_array(Mage::app()->getFrontController()->getAction()->getFullActionName(), $allowedActionNameList) && $category && $category->getId();
    }
 public function getCurrentCategoryId() {
  return Mage::registry('current_category')->getId();
 }
    public function isCheckoutPage()
    {
        $allowedActionNameList = array(
            'checkout_onepage_index',
            'checkout_multishipping_login',
            'checkout_multishipping_index',
        );
        return in_array(Mage::app()->getFrontController()->getAction()->getFullActionName(), $allowedActionNameList);
    }
    public function isCartPage()
    {
        $allowedActionNameList = array(
            'checkout_cart_index',
        );
        return in_array(Mage::app()->getFrontController()->getAction()->getFullActionName(), $allowedActionNameList);
    }
    public function isAccountPage()
    {
        $customerAccountHandle = 'customer_account';
        if (in_array($customerAccountHandle, Mage::app()->getLayout()->getUpdate()->getHandles())) {
            return true;
        }
        $allowedActionNameList = array(
            'customer_account_logoutSuccess',
            'customer_account_login',
            'customer_account_create',
        );
        return in_array(Mage::app()->getFrontController()->getAction()->getFullActionName(), $allowedActionNameList);
    }
    public function isOtherPage()
    {
        return !$this->isHomePage() && !$this->isProductPage() && $this->isCmsPage() && !$this->isCategoryPage() && !$this->isCheckoutPage() && !$this->isCartPage() && !$this->isAccountPage();
    }
}

Step 21: Create file in app/code/community/Vijay/CustomBackground/Helper/Config.php and add below code in it.

<?php

class Vijay_CustomBackground_Helper_Config extends Mage_Core_Helper_Data
{
    const GENERAL_IS_ENABLED = 'vijay_custombackground/general/is_enabled';
    
    /**
     * @param null|int|Mage_Core_Model_Store $store
     *
     * @return bool
     */
    public function isEnabled($store = null)
    {
        $isConfigEnabled = Mage::getStoreConfigFlag(self::GENERAL_IS_ENABLED, $store);
        $isModuleEnabled = $this->isModuleEnabled();
        $isModuleOutputEnabled = $this->isModuleOutputEnabled();
        return $isConfigEnabled && $isModuleEnabled && $isModuleOutputEnabled;
    }
}

Step 22: Create file in app/code/community/Vijay/CustomBackground/Helper/Image/Abstract.php and add below code in it.

<?php

abstract class Vijay_CustomBackground_Helper_Image_Abstract extends Mage_Core_Helper_Data
{
    /**
     * path to image placeholder
     * override in child
     * @var string
     */
    protected $_placeholder     = '';

    /**
     * subdirectory to save imaves
     * override in child
     * @var string
     */
    protected $_subdir          = '';

    /**
     * image processor
     * @var null|Varien_Image_Adapter_Gd2
     */
    protected $_imageProcessor     = null;

    /**
     * image to process
     * @var unknown_type
     */
    protected $_image             = null;

    /**
     * error message
     * @var string
     */
    protected $_openError         = "";

    /**
     * keep image frame
     * @var bool
     */
    protected $_keepFrame       = false;

    /**
     * keep image aspect ratio
     * @var bool
     */
    protected $_keepAspectRatio = true;

    /**
     * constrain image
     * @var bool
     */
    protected $_constrainOnly   = true;

    /**
     * addaptive resize - crop
     * https://github.com/wearefarm/magento-adaptive-resize/blob/master/README.md
     * @var bool
     */
    protected $_adaptiveResize  = 'center'; // false|center|top|bottom

    /**
     * image width
     * @var mixed(null|int)
     */
    protected $_width           = null;

    /**
     * image height
     * @var mixed(null|int)
     */
    protected $_height          = null;

    /**
     * image resize needed
     * @var mixed (null|array)
     */
    protected $_scheduledResize = null;

    /**
     * image is resized
     * @var bool
     */
    protected $_resized         = false;

    /**
     * addaptive resize positions
     * https://github.com/wearefarm/magento-adaptive-resize/blob/master/README.md
     * @var array
     */
    protected $_adaptiveResizePositions = array(
        'center' => array(0.5,0.5),
        'top'    => array(1,0),
        'bottom' => array(0,1)
    );

    /**
     * resized image folder name
     * @var string
     */
    protected $_resizeFolderName = 'cache';

    /**
     * get the image base dir
     *
     * @access public
     * @return string
     * @author Ultimate Module Creator
     */
    public function getImageBaseDir()
    {
        return Mage::getBaseDir('media').DS.$this->_subdir.DS.'image';
    }

    /**
     * get the image url for object
     *
     * @access public
     * @return string
     * @author Ultimate Module Creator
     */
    public function getImageBaseUrl()
    {
        return Mage::getBaseUrl('media').$this->_subdir.'/'.'image';
    }

    /**
     * init image
     *
     * @access public
     * @param Varien_Object $object
     * @param string $imageField
     * @return Vijay_CustomBackground_Helper_Image_Abstract
     * @author Ultimate Module Creator
     */
    public function init(Varien_Object $object, $imageField = 'image')
    {
        $this->_imageProcessor = null;
        $this->_image = $object->getDataUsingMethod($imageField);
        if (!$this->_image) {
            $this->_image = '/'.$this->_placeholder;
        }
        $this->_width = null;
        $this->_height = null;
        $this->_scheduledResize = false;
        $this->_resized = false;
        $this->_adaptiveResize = 'center';

        try {
            $this->_getImageProcessor()->open($this->getImageBaseDir().$this->_image);
        } catch (Exception $e) {
            $this->_openError = $e->getMessage();
            try {
                $this->_getImageProcessor()->open(Mage::getDesign()->getSkinUrl($this->_placeholder));
                $this->_image = '/'.$this->_placeholder;
            } catch(Exception $e) {
                $this->_openError .= "\n".$e->getMessage();
                $this->_image = null;
            }
        }
        return $this;
    }

    /**
     * get the image processor
     *
     * @access protected
     * @return Varien_Image_Adapter_Gd2
     * @author Ultimate Module Creator
     */
    protected function _getImageProcessor()
    {
        if (is_null($this->_imageProcessor)) {
            $this->_imageProcessor = Varien_Image_Adapter::factory('GD2');
            $this->_imageProcessor->keepFrame($this->_keepFrame);
            $this->_imageProcessor->keepAspectRatio($this->_keepAspectRatio);
            $this->_imageProcessor->constrainOnly($this->_constrainOnly);
        }
        return $this->_imageProcessor;
    }

    /**
     * Get/set keepAspectRatio
     *
     * @access public
     * @param bool $value
     * @return mixed(bool|Vijay_CustomBackground_Helper_Image_Abstract)
     * @author Ultimate Module Creator
     */
    public function keepAspectRatio($value = null)
    {
        if (null !== $value) {
            $this->_getImageProcessor()->keepAspectRatio($value);
            return $this;
        } else {
            return $this->_getImageProcessor()->keepAspectRatio();
        }
    }

    /**
     * Get/set keepFrame
     *
     * @access public
     * @param bool $value
     * @return mixed(bool|Vijay_CustomBackground_Helper_Image_Abstract)
     * @author Ultimate Module Creator
     */
    public function keepFrame($value = null)
    {
        if (null !== $value) {
            $this->_getImageProcessor()->keepFrame($value);
            return $this;
        } else {
            return $this->_getImageProcessor()->keepFrame();
        }
    }

    /**
     * Get/set keepTransparency
     *
     * @access public
     * @param bool $value
     * @return mixed(bool|Vijay_CustomBackground_Helper_Image_Abstract)
     * @author Ultimate Module Creator
     */
    public function keepTransparency($value = null)
    {
        if (null !== $value) {
            $this->_getImageProcessor()->keepTransparency($value);
            return $this;
        } else {
            return $this->_getImageProcessor()->keepTransparency();
        }
    }

    /**
     * Get/set adaptiveResize
     *
     * @access public
     * @param bool|string $value
     * @return mixed(bool|Vijay_CustomBackground_Helper_Image_Abstract)
     * https://github.com/wearefarm/magento-adaptive-resize/blob/master/README.md
     * @author Ultimate Module Creator
     */
    public function adaptiveResize($value = null)
    {
        if (null !== $value) {
            $this->_adaptiveResize = $value;
            if ($value) {
                $this->keepFrame(false);
            }
            return $this;
        } else {
            return $this->_adaptiveResize;
        }
    }

    /**
     * Get/set constrainOnly
     *
     * @access public
     * @param bool $value
     * @return mixed(bool|Vijay_CustomBackground_Helper_Image_Abstract)
     * @author Ultimate Module Creator
     */
    public function constrainOnly($value = null)
    {
       if (null !== $value) {
            $this->_getImageProcessor()->constrainOnly($value);
            return $this;
       } else {
            return $this->_getImageProcessor()->constrainOnly();
       }
    }

    /**
     * Get/set quality, values in percentage from 0 to 100
     *
     * @access public
     * @param int $value
     * @return mixed(bool|Vijay_CustomBackground_Helper_Image_Abstract)
     * @author Ultimate Module Creator
     */
    public function quality($value = null)
    {
        if (null !== $value) {
            $this->_getImageProcessor()->quality($value);
            return $this;
        } else {
            return $this->_getImageProcessor()->quality();
        }
    }

    /**
     * Get/set keepBackgroundColor
     *
     * @access public
     * @param array $value
     * @return mixed(bool|Vijay_CustomBackground_Helper_Image_Abstract)
     * @author Ultimate Module Creator
     */
    public function backgroundColor($value = null)
    {
        if (null !== $value) {
            $this->_getImageProcessor()-> backgroundColor($value);
            return $this;
        } else {
            return $this->_getImageProcessor()-> backgroundColor();
        }
    }

    /**
     * resize image
     *
     * @access public
     * @param int $width - defaults to null
     * @param int $height - defaults to null
     * @return Vijay_CustomBackground_Helper_Image_Abstract
     * @author Ultimate Module Creator
     */
    public function resize($width = null, $height = null)
    {
        $this->_scheduledResize = true;
        $this->_width  = $width;
        $this->_height = $height;
        return $this;
    }

    /**
     * get destination image prefix
     *
     * @access protected
     * @return Vijay_CustomBackground_Helper_Image_Abstract
     * @author Ultimate Module Creator
     */
    protected function _getDestinationImagePrefix()
    {
        if (!$this->_image) {
            return $this;
        }
        $imageRealPath = "";
        if ($this->_scheduledResize) {
            $width  = $this->_width;
            $height = $this->_height;
            $adaptive   = $this->adaptiveResize();
            $keepFrame  = $this->keepFrame();
            $keepAspectRatio= $this->keepAspectRatio();
            $constrainOnly  = $this->constrainOnly();
            $imageRealPath = $width.'x'.$height;
            $options = "";

            if (!$keepAspectRatio) {
                $imageRealPath .= '-exact';
            } else {
                if (!$keepFrame && $width && $height && ($adaptive !== false)) {
                    $adaptive = strtolower(trim($adaptive));
                    if (isset($this->_adaptiveResizePositions[$adaptive])) {
                        $imageRealPath .= '-'.$adaptive;
                    }
                }
            }
            if ($keepFrame) {
                $imageRealPath .= '-frame';
                $_backgroundColor = $this->backgroundColor();
                if ($_backgroundColor) {
                    $imageRealPath .= '-'.implode('-', $_backgroundColor);
                }
            }
            if (!$constrainOnly) {
                $imageRealPath .= '-zoom';
            }
        }
        return $imageRealPath;
    }

    /**
     * get image destination path
     *
     * @access protected
     * @return string
     * @author Ultimate Module Creator
     */
    protected function _getDestinationPath()
    {
        if (!$this->_image) {
            return $this;
        }
        if ($this->_scheduledResize) {
            return $this->getImageBaseDir().DS.$this->_resizeFolderName.DS.$this->_getDestinationImagePrefix().DS.$this->_image;
        } else {
            return $this->getImageBaseDir().DS.$this->_image;
        }
    }

    /**
     * get image url
     *
     * @access protected
     * @return mixed (string|bool)
     * @author Ultimate Module Creator
     */
    protected function _getImageUrl()
    {
        if (!$this->_image) {
            return false;
        }
        if ($this->_scheduledResize) {
            return  $this->getImageBaseUrl().'/'.$this->_resizeFolderName.'/'.$this->_getDestinationImagePrefix().$this->_image;
        } else {
           return  $this->getImageBaseUrl().$this->_image;
        }
    }

    /**
     * resize image
     *
     * @access protected
     * @return Vijay_CustomBackground_Helper_Image_Abstract
     * @author Ultimate Module Creator
     */
    protected function _doResize()
    {
        if (!$this->_image || !$this->_scheduledResize || $this->_resized) {
            return $this;
        }
        $this->_resized = true; //mark as resized
        $width = $this->_width;
        $height = $this->_height;
        $adaptive = $width && $height &&
                    $this->keepAspectRatio() && !$this->keepFrame() &&
                    ($this->adaptiveResize() !== false);
        $adaptivePosition = false;
        if ($adaptive) {
            $adaptive = strtolower(trim($this->adaptiveResize()));
            if (isset($this->_adaptiveResizePositions[$adaptive])) {
                $adaptivePosition = $this->_adaptiveResizePositions[$adaptive];
            }
        }
        $processor = $this->_getImageProcessor();

        if (!$adaptivePosition) {
            $processor->resize($width, $height);
            return $this;
        }
        //make adaptive resize
        //https://github.com/wearefarm/magento-adaptive-resize/blob/master/README.md
        $currentRatio = $processor->getOriginalWidth() / $processor->getOriginalHeight();
        $targetRatio  = $width / $height;
        if ($targetRatio > $currentRatio) {
            $processor->resize($width, null);
        } else {
            $processor->resize(null, $height);
        }
        $diffWidth  = $processor->getOriginalWidth() - $width;
        $diffHeight = $processor->getOriginalHeight() - $height;
        if ($diffWidth || $diffHeight) {
            $processor->crop(
                floor($diffHeight * $adaptivePosition[0]), //top rate
                floor($diffWidth / 2),
                ceil($diffWidth / 2),
                ceil($diffHeight *  $adaptivePosition[1]) //bottom rate
            );
        }
        return $this;
    }

    /**
     * to string - no need for cache expire because the image names will be different
     *
     * @access public
     * @return string
     * @author Ultimate Module Creator
     */
    public function __toString()
    {
        try {
            if (!$this->_image) {
                throw new Exception($this->_openError);
            }
            $imageRealPath = $this->_getDestinationPath();
            if (!file_exists($imageRealPath)) {
                $this->_doResize();
                $this->_getImageProcessor()->save($imageRealPath);
            }
            return $this->_getImageUrl();
        } catch (Exception $e) {
            Mage::logException($e);
            return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAFr0lEQVR42rWXaUxUZxSGZVOKpWBRCGrSijBgDG1dagaxVgNSUqhAqq1CqzVVksb+sdZU0hgbfhQ1riEoiHFns4qVEYWglEWgVaBQLXRYJKzCzCA7KCpvz7njHbgz4AXSkryZYea73/Oe5Tv3zhQABtGfGcmCZPk/yYIZEuYIuDnJgeRKcn8pj/9Q7rw3M5g1moFpJGVnVxe0Wi20Oh107e1of/wYj1kdHejo7AR/z+oS1d0tqLunx6AeVm+vifoHBsAMZo1lYKVWq0NzyyO0PGrFo9Y2tLZp0KYRDA2bMjamN6c3OGzSxGwvmWDGWAasSR9qde0EbiVwG4E10AxnQw/XQ1nDUAYZZ2QU9fX1gRnMGtMAASTwMUvBGoYyQFoClmkJ5A0QhOHSlEtTbQoeAewVRdGy+kZoYDwGCGSacmOwKVQK6+9H/yh68uSJvAGGCGBTuACur6pCXUICssPDcXfHDvy5dy8KIyLQdOkSmh8+FNI8YCwCs54+fSpvgCNkOJeiwwieHROD3KBP8CDyJ9QePYLq/fuhjoqCml7L9/yI236+yI+L40hZDJRocHBwXAZGjTztq00o+mYbKiIj8cf2cGT6rIJKqUTakiW44a1EwdYtKNm1C/lfboBq0xcMM9GzZ8/kDRDMBJ5FkWeHrkPJD7uQvsYb177egr/LyzndQhPmpqYi2c0Fv23aiPxt25AZHIi8kycnZ4CaS1rz2lpcXbEUhd9ux7VVSmSfO8d1NaSY36cGBSJzrT9uhYYia+PnyFy/Dul+K6FpbmaoQc+fP5c3wF0twtnM5d27cfPTAEFJYRskcH69vjkMBaEh1BtBuEX9kbJIgav+q5EW6Iu0PXsYatCLFy/kDfCR4j7g1PIxSwwm+PogJCo98c/9+1L41s24FxaCIh8f5K3xwdVlC3CeTkTCewqkBvjhSthnkzMgwvn9WS9PpH7kh3Pve4yE0+brURLsixJqxOIPvKHyWoicM2eEWscrZuPI3Dk4tciNoRLJGuCB0q0fMMJQOb5YgQMz7BHj5mQYJvE+3shdqkDpvHkonz8PqmUKZJ8+zQAh0ti3HbDPbAriFusNDA0NscZngKFC9C8n2sm1foh6wwqHZ9vgdnIyYlZ5QeVojd/p0r+szHHZxR5Z8fGGCCtKSxHnZI1ouuZsyMcMlkjWAEN79dELEV/4ficOzZmOE7TpPlcnpDrb4A5d9oDgv7ja42ZcrAHOgLggfyTMskbsXBukROyeeAkYKkbPHd9UX48DHjMRa0lAgmfQJXenmiPFfQauH4+RwH89fBgXXGyRTOaOLpiFlsbGic8BHi5i9GyAm+7yoYOIUdghiZbfmmqBC++8iWiaCyJcXVaG6ABfpNCaLDJ32s0OV+ga2oP3Eu+QvJ/8A8mA3oDkvLP7Q8H+OOVB9ba2QKHja8icb4vEBTNx0cMB11xex10q071pFjhPa47QWuojPs58P+H7Cov/HyLGcjkD7Fw0IElf0oH9OOjpiBvudihztEG1uRnqSGoylE3RH/N0wsWon4WHFY1Gg5aWFjQ1NaGhoRH19Q1QqVR3iPEWyVzOgJh+iQFWQ10dTuz8DvsCVuOY0gXRXvNxNMQfsfRZjVotwGtpfBcWFqKoqAjldM+oqKhguJr2X0iayjw5Axy9sYGRE01yvvk7vo4HGEeel5fHnwt1r6qqYngj7b1IbD45Ayb1Z4DUgHS48BqGcb055Tk5uUIfVVdXIyMjQ2tra7uC9p7OHHkDBB7bgGn0/Bmv5ej5QaaOSlRcXIyamhoB7uzs7Ef72jJjogaM6//K9HPH63Q6qKkPKisrkZ6e3kiRL2c4yUzWgPjDZCIGAEgM0C8qNsBwbrh3STZSoLyB5QR8Ve1HKwGv5x7gsz5E8AL+HSie9YkYsHx5Rr25FJOUF2kuyUoCkjUgNcGZsJ6kpolDZrz6F2ZUsalEFcbPAAAAAElFTkSuQmCC';
        }
    }
}

Step 23: Create file in app/code/community/Vijay/CustomBackground/Helper/Background/Image.php and add below code in it.

<?php

class Vijay_CustomBackground_Helper_Background_Image extends Vijay_CustomBackground_Helper_Image_Abstract
{
    /**
     * image placeholder
     * @var string
     */
    protected $_placeholder = 'images/placeholder/background.jpg';
    /**
     * image subdir
     * @var string
     */
    protected $_subdir      = 'background';
}

Step 24: Create file in app/code/community/Vijay/CustomBackground/Model/Adminhtml/Search/Background.php and add below code in it.

<?php

class Vijay_CustomBackground_Model_Adminhtml_Search_Background extends Varien_Object
{
    /**
     * Load search results
     *
     * @access public
     * @return Vijay_CustomBackground_Model_Adminhtml_Search_Background
     * @author Ultimate Module Creator
     */
    public function load()
    {
        $arr = array();
        if (!$this->hasStart() || !$this->hasLimit() || !$this->hasQuery()) {
            $this->setResults($arr);
            return $this;
        }
        $collection = Mage::getResourceModel('vijay_custombackground/background_collection')
            ->addFieldToFilter('background_name', array('like' => $this->getQuery().'%'))
            ->setCurPage($this->getStart())
            ->setPageSize($this->getLimit())
            ->load();
        foreach ($collection->getItems() as $background) {
            $arr[] = array(
                'id'          => 'background/1/'.$background->getId(),
                'type'        => Mage::helper('vijay_custombackground')->__('Background'),
                'name'        => $background->getBackgroundName(),
                'description' => $background->getBackgroundName(),
                'url' => Mage::helper('adminhtml')->getUrl(
                    '*/custombackground_background/edit',
                    array('id'=>$background->getId())
                ),
            );
        }
        $this->setResults($arr);
        return $this;
    }
}

Step 25: Create file in app/code/community/Vijay/CustomBackground/Model/Background/Attribute/Source/Backgroundattachment.php and add below code in it.

<?php

class Vijay_CustomBackground_Model_Background_Attribute_Source_Backgroundattachment extends Mage_Eav_Model_Entity_Attribute_Source_Table
{
    /**
     * get possible values
     *
     * @access public
     * @param bool $withEmpty
     * @param bool $defaultValues
     * @return array
     * @author Ultimate Module Creator
     */
    public function getAllOptions($withEmpty = true, $defaultValues = false)
    {
        $options =  array(
            array(
                'label' => Mage::helper('vijay_custombackground')->__('scroll'),
                'value' => 'scroll'
            ),
            array(
                'label' => Mage::helper('vijay_custombackground')->__('fixed'),
                'value' => 'fixed'
            ),
            array(
                'label' => Mage::helper('vijay_custombackground')->__('local'),
                'value' => 'local'
            ),
            array(
                'label' => Mage::helper('vijay_custombackground')->__('initial'),
                'value' => 'initial'
            ),
            array(
                'label' => Mage::helper('vijay_custombackground')->__('inherit'),
                'value' => 'inherit'
            ),
        );
        if ($withEmpty) {
            array_unshift($options, array('label'=>'', 'value'=>''));
        }
        return $options;

    }

    /**
     * get options as array
     *
     * @access public
     * @param bool $withEmpty
     * @return string
     * @author Ultimate Module Creator
     */
    public function getOptionsArray($withEmpty = true)
    {
        $options = array();
        foreach ($this->getAllOptions($withEmpty) as $option) {
            $options[$option['value']] = $option['label'];
        }
        return $options;
    }

    /**
     * get option text
     *
     * @access public
     * @param mixed $value
     * @return string
     * @author Ultimate Module Creator
     */
    public function getOptionText($value)
    {
        $options = $this->getOptionsArray();
        if (!is_array($value)) {
            $value = explode(',', $value);
        }
        $texts = array();
        foreach ($value as $v) {
            if (isset($options[$v])) {
                $texts[] = $options[$v];
            }
        }
        return implode(', ', $texts);
    }
}

Step 26: Create file in app/code/community/Vijay/CustomBackground/Model/Background/Attribute/Source/Backgroundclip.php and add below code in it.

<?php

class Vijay_CustomBackground_Model_Background_Attribute_Source_Backgroundclip extends Mage_Eav_Model_Entity_Attribute_Source_Table
{
    /**
     * get possible values
     *
     * @access public
     * @param bool $withEmpty
     * @param bool $defaultValues
     * @return array
     * @author Ultimate Module Creator
     */
    public function getAllOptions($withEmpty = true, $defaultValues = false)
    {
        $options =  array(
            array(
                'label' => Mage::helper('vijay_custombackground')->__('border-box'),
                'value' => 'border-box'
            ),
            array(
                'label' => Mage::helper('vijay_custombackground')->__('padding-box'),
                'value' => 'padding-box'
            ),
            array(
                'label' => Mage::helper('vijay_custombackground')->__('content-box'),
                'value' => 'content-box'
            ),
            array(
                'label' => Mage::helper('vijay_custombackground')->__('initial'),
                'value' => 'initial'
            ),
            array(
                'label' => Mage::helper('vijay_custombackground')->__('inherit'),
                'value' => 'inherit'
            ),
        );
        if ($withEmpty) {
            array_unshift($options, array('label'=>'', 'value'=>''));
        }
        return $options;

    }

    /**
     * get options as array
     *
     * @access public
     * @param bool $withEmpty
     * @return string
     * @author Ultimate Module Creator
     */
    public function getOptionsArray($withEmpty = true)
    {
        $options = array();
        foreach ($this->getAllOptions($withEmpty) as $option) {
            $options[$option['value']] = $option['label'];
        }
        return $options;
    }

    /**
     * get option text
     *
     * @access public
     * @param mixed $value
     * @return string
     * @author Ultimate Module Creator
     */
    public function getOptionText($value)
    {
        $options = $this->getOptionsArray();
        if (!is_array($value)) {
            $value = explode(',', $value);
        }
        $texts = array();
        foreach ($value as $v) {
            if (isset($options[$v])) {
                $texts[] = $options[$v];
            }
        }
        return implode(', ', $texts);
    }
}

Step 27: Create file in app/code/community/Vijay/CustomBackground/Model/Background/Attribute/Source/Backgroundorigin.php and add below code in it.

<?php

class Vijay_CustomBackground_Model_Background_Attribute_Source_Backgroundorigin extends Mage_Eav_Model_Entity_Attribute_Source_Table
{
    /**
     * get possible values
     *
     * @access public
     * @param bool $withEmpty
     * @param bool $defaultValues
     * @return array
     * @author Ultimate Module Creator
     */
    public function getAllOptions($withEmpty = true, $defaultValues = false)
    {
        $options =  array(
            array(
                'label' => Mage::helper('vijay_custombackground')->__('padding-box'),
                'value' => 'padding-box'
            ),
            array(
                'label' => Mage::helper('vijay_custombackground')->__('border-box'),
                'value' => 'border-box'
            ),
            array(
                'label' => Mage::helper('vijay_custombackground')->__('content-box'),
                'value' => 'content-box'
            ),
            array(
                'label' => Mage::helper('vijay_custombackground')->__('initial'),
                'value' => 'initial'
            ),
            array(
                'label' => Mage::helper('vijay_custombackground')->__('inherit'),
                'value' => 'inherit'
            ),
        );
        if ($withEmpty) {
            array_unshift($options, array('label'=>'', 'value'=>''));
        }
        return $options;

    }

    /**
     * get options as array
     *
     * @access public
     * @param bool $withEmpty
     * @return string
     * @author Ultimate Module Creator
     */
    public function getOptionsArray($withEmpty = true)
    {
        $options = array();
        foreach ($this->getAllOptions($withEmpty) as $option) {
            $options[$option['value']] = $option['label'];
        }
        return $options;
    }

    /**
     * get option text
     *
     * @access public
     * @param mixed $value
     * @return string
     * @author Ultimate Module Creator
     */
    public function getOptionText($value)
    {
        $options = $this->getOptionsArray();
        if (!is_array($value)) {
            $value = explode(',', $value);
        }
        $texts = array();
        foreach ($value as $v) {
            if (isset($options[$v])) {
                $texts[] = $options[$v];
            }
        }
        return implode(', ', $texts);
    }
}

Step 28: Create file in app/code/community/Vijay/CustomBackground/Model/Background/Attribute/Source/Backgroundposition.php and add below code in it.

<?php

class Vijay_CustomBackground_Model_Background_Attribute_Source_Backgroundposition extends Mage_Eav_Model_Entity_Attribute_Source_Table
{
    /**
     * get possible values
     *
     * @access public
     * @param bool $withEmpty
     * @param bool $defaultValues
     * @return array
     * @author Ultimate Module Creator
     */
    public function getAllOptions($withEmpty = true, $defaultValues = false)
    {
        $options =  array(
            array(
                'label' => Mage::helper('vijay_custombackground')->__('left top'),
                'value' => 'left top'
            ),
            array(
                'label' => Mage::helper('vijay_custombackground')->__('left center'),
                'value' => 'left center'
            ),
            array(
                'label' => Mage::helper('vijay_custombackground')->__('left bottom'),
                'value' => 'left bottom'
            ),
            array(
                'label' => Mage::helper('vijay_custombackground')->__('right top'),
                'value' => 'right top'
            ),
            array(
                'label' => Mage::helper('vijay_custombackground')->__('right center'),
                'value' => 'right center'
            ),
            array(
                'label' => Mage::helper('vijay_custombackground')->__('right bottom'),
                'value' => 'right bottom'
            ),
            array(
                'label' => Mage::helper('vijay_custombackground')->__('center top'),
                'value' => 'center top'
            ),
            array(
                'label' => Mage::helper('vijay_custombackground')->__('center center'),
                'value' => 'center center'
            ),
            array(
                'label' => Mage::helper('vijay_custombackground')->__('center bottom'),
                'value' => 'center bottom'
            ),
        );
        if ($withEmpty) {
            array_unshift($options, array('label'=>'', 'value'=>''));
        }
        return $options;

    }

    /**
     * get options as array
     *
     * @access public
     * @param bool $withEmpty
     * @return string
     * @author Ultimate Module Creator
     */
    public function getOptionsArray($withEmpty = true)
    {
        $options = array();
        foreach ($this->getAllOptions($withEmpty) as $option) {
            $options[$option['value']] = $option['label'];
        }
        return $options;
    }

    /**
     * get option text
     *
     * @access public
     * @param mixed $value
     * @return string
     * @author Ultimate Module Creator
     */
    public function getOptionText($value)
    {
        $options = $this->getOptionsArray();
        if (!is_array($value)) {
            $value = explode(',', $value);
        }
        $texts = array();
        foreach ($value as $v) {
            if (isset($options[$v])) {
                $texts[] = $options[$v];
            }
        }
        return implode(', ', $texts);
    }
}

Step 29: Create file in app/code/community/Vijay/CustomBackground/Model/Background/Attribute/Source/Backgroundrepeat.php and add below code in it.

<?php

class Vijay_CustomBackground_Model_Background_Attribute_Source_Backgroundrepeat extends Mage_Eav_Model_Entity_Attribute_Source_Table
{
    /**
     * get possible values
     *
     * @access public
     * @param bool $withEmpty
     * @param bool $defaultValues
     * @return array
     * @author Ultimate Module Creator
     */
    public function getAllOptions($withEmpty = true, $defaultValues = false)
    {
        $options =  array(
            array(
                'label' => Mage::helper('vijay_custombackground')->__('repeat'),
                'value' => 'repeat'
            ),
            array(
                'label' => Mage::helper('vijay_custombackground')->__('repeat-x'),
                'value' => 'repeat-x'
            ),
            array(
                'label' => Mage::helper('vijay_custombackground')->__('repeat-y'),
                'value' => 'repeat-y'
            ),
            array(
                'label' => Mage::helper('vijay_custombackground')->__('no-repeat'),
                'value' => 'no-repeat'
            ),
            array(
                'label' => Mage::helper('vijay_custombackground')->__('initial'),
                'value' => 'initial'
            ),
            array(
                'label' => Mage::helper('vijay_custombackground')->__('inherit'),
                'value' => 'inherit'
            ),
        );
        if ($withEmpty) {
            array_unshift($options, array('label'=>'', 'value'=>''));
        }
        return $options;

    }

    /**
     * get options as array
     *
     * @access public
     * @param bool $withEmpty
     * @return string
     * @author Ultimate Module Creator
     */
    public function getOptionsArray($withEmpty = true)
    {
        $options = array();
        foreach ($this->getAllOptions($withEmpty) as $option) {
            $options[$option['value']] = $option['label'];
        }
        return $options;
    }

    /**
     * get option text
     *
     * @access public
     * @param mixed $value
     * @return string
     * @author Ultimate Module Creator
     */
    public function getOptionText($value)
    {
        $options = $this->getOptionsArray();
        if (!is_array($value)) {
            $value = explode(',', $value);
        }
        $texts = array();
        foreach ($value as $v) {
            if (isset($options[$v])) {
                $texts[] = $options[$v];
            }
        }
        return implode(', ', $texts);
    }
}

Step 30: Create file in app/code/community/Vijay/CustomBackground/Model/Background/Attribute/Source/Backgroundsize.php and add below code in it.

<?php

class Vijay_CustomBackground_Model_Background_Attribute_Source_Backgroundsize extends Mage_Eav_Model_Entity_Attribute_Source_Table
{
    /**
     * get possible values
     *
     * @access public
     * @param bool $withEmpty
     * @param bool $defaultValues
     * @return array
     * @author Ultimate Module Creator
     */
    public function getAllOptions($withEmpty = true, $defaultValues = false)
    {
        $options =  array(
            array(
                'label' => Mage::helper('vijay_custombackground')->__('auto'),
                'value' => 'auto'
            ),
            array(
                'label' => Mage::helper('vijay_custombackground')->__('length'),
                'value' => 'length'
            ),
            array(
                'label' => Mage::helper('vijay_custombackground')->__('cover'),
                'value' => 'cover'
            ),
            array(
                'label' => Mage::helper('vijay_custombackground')->__('contain'),
                'value' => 'contain'
            ),
            array(
                'label' => Mage::helper('vijay_custombackground')->__('initial'),
                'value' => 'initial'
            ),
            array(
                'label' => Mage::helper('vijay_custombackground')->__('inherit'),
                'value' => 'inherit'
            ),
        );
        if ($withEmpty) {
            array_unshift($options, array('label'=>'', 'value'=>''));
        }
        return $options;

    }

    /**
     * get options as array
     *
     * @access public
     * @param bool $withEmpty
     * @return string
     * @author Ultimate Module Creator
     */
    public function getOptionsArray($withEmpty = true)
    {
        $options = array();
        foreach ($this->getAllOptions($withEmpty) as $option) {
            $options[$option['value']] = $option['label'];
        }
        return $options;
    }

    /**
     * get option text
     *
     * @access public
     * @param mixed $value
     * @return string
     * @author Ultimate Module Creator
     */
    public function getOptionText($value)
    {
        $options = $this->getOptionsArray();
        if (!is_array($value)) {
            $value = explode(',', $value);
        }
        $texts = array();
        foreach ($value as $v) {
            if (isset($options[$v])) {
                $texts[] = $options[$v];
            }
        }
        return implode(', ', $texts);
    }
}

Step 31: Create file in app/code/community/Vijay/CustomBackground/Model/Background/Attribute/Source/Backgroundtarget.php and add below code in it.

<?php

class Vijay_CustomBackground_Model_Background_Attribute_Source_Backgroundtarget extends Mage_Eav_Model_Entity_Attribute_Source_Table
{
    /**
     * get possible values
     *
     * @access public
     * @param bool $withEmpty
     * @param bool $defaultValues
     * @return array
     * @author Ultimate Module Creator
     */
    public function getAllOptions($withEmpty = true, $defaultValues = false)
    {
        $options =  array(
            array(
                'label' => Mage::helper('vijay_custombackground')->__('Wrapper'),
                'value' => '.wrapper'
            ),
            array(
                'label' => Mage::helper('vijay_custombackground')->__('Body'),
                'value' => 'body'
            ),
            array(
                'label' => Mage::helper('vijay_custombackground')->__('Custom CSS selector'),
                'value' => 'custom'
            ),
        );
        if ($withEmpty) {
            array_unshift($options, array('label'=>'', 'value'=>''));
        }
        return $options;

    }

    /**
     * get options as array
     *
     * @access public
     * @param bool $withEmpty
     * @return string
     * @author Ultimate Module Creator
     */
    public function getOptionsArray($withEmpty = true)
    {
        $options = array();
        foreach ($this->getAllOptions($withEmpty) as $option) {
            $options[$option['value']] = $option['label'];
        }
        return $options;
    }

    /**
     * get option text
     *
     * @access public
     * @param mixed $value
     * @return string
     * @author Ultimate Module Creator
     */
    public function getOptionText($value)
    {
        $options = $this->getOptionsArray();
        if (!is_array($value)) {
            $value = explode(',', $value);
        }
        $texts = array();
        foreach ($value as $v) {
            if (isset($options[$v])) {
                $texts[] = $options[$v];
            }
        }
        return implode(', ', $texts);
    }
}

Step 32: Create file in app/code/community/Vijay/CustomBackground/Model/Background/Attribute/Source/Backgroundtargettype.php and add below code in it.

<?php

class Vijay_CustomBackground_Model_Background_Attribute_Source_Backgroundtargettype extends Mage_Eav_Model_Entity_Attribute_Source_Table
{
    /**
     * get possible values
     *
     * @access public
     * @param bool $withEmpty
     * @param bool $defaultValues
     * @return array
     * @author Ultimate Module Creator
     */
    public function getAllOptions($withEmpty = true, $defaultValues = false)
    {
        $options =  array(
            array(
                'label' => Mage::helper('vijay_custombackground')->__('CMS'),
                'value' => 1
            ),
            array(
                'label' => Mage::helper('vijay_custombackground')->__('Product View'),
                'value' => 2
            ),
            array(
                'label' => Mage::helper('vijay_custombackground')->__('Category View'),
                'value' => 3
            ),
            array(
                'label' => Mage::helper('vijay_custombackground')->__('Customer Pages'),
                'value' => 4
            ),
            array(
                'label' => Mage::helper('vijay_custombackground')->__('Home Page'),
                'value' => 5
            ),
            array(
                'label' => Mage::helper('vijay_custombackground')->__('Checkout'),
                'value' => 6
            ),
            array(
                'label' => Mage::helper('vijay_custombackground')->__('Cart'),
                'value' => 7
            ),
            array(
                'label' => Mage::helper('vijay_custombackground')->__('Other Page'),
                'value' => 8
            ),
        );
        if ($withEmpty) {
            array_unshift($options, array('label'=>'', 'value'=>''));
        }
        return $options;

    }

    /**
     * get options as array
     *
     * @access public
     * @param bool $withEmpty
     * @return string
     * @author Ultimate Module Creator
     */
    public function getOptionsArray($withEmpty = true)
    {
        $options = array();
        foreach ($this->getAllOptions($withEmpty) as $option) {
            $options[$option['value']] = $option['label'];
        }
        return $options;
    }

    /**
     * get option text
     *
     * @access public
     * @param mixed $value
     * @return string
     * @author Ultimate Module Creator
     */
    public function getOptionText($value)
    {
        $options = $this->getOptionsArray();
        if (!is_array($value)) {
            $value = explode(',', $value);
        }
        $texts = array();
        foreach ($value as $v) {
            if (isset($options[$v])) {
                $texts[] = $options[$v];
            }
        }
        return implode(', ', $texts);
    }
}

Step 33: Create file in app/code/community/Vijay/CustomBackground/Model/Background/Attribute/Source/Productcategories.php and add below code in it.

<?php

class Vijay_CustomBackground_Model_Background_Attribute_Source_Productcategories extends Varien_Object
{
    const REPEATER = '_';
    const PREFIX_END = '';
    protected $_options = array();
    /**
     * @param int $parentId
     * @param int $recursionLevel
     *
     * @return array
     */
    public function getOptionArray($parentId = 1, $recursionLevel = 3)
    {
        $recursionLevel = (int)$recursionLevel;
        $parentId       = (int)$parentId;
        $category = Mage::getModel('catalog/category');
        /* @var $category Mage_Catalog_Model_Category */
        
        //$storeCategories = $category->getCategories($parentId, $recursionLevel, TRUE, FALSE, TRUE);
  $storeCategories = $category->getCategories($parentId, $recursionLevel, TRUE, FALSE, TRUE);
  
        foreach ($storeCategories as $node) {
          
            /* @var $node Varien_Data_Tree_Node */
            if($node->getEntityId() == 2) {
       $this->_options = '';
     } else {
      $this->_options[] = array(
                'label' => $node->getName(),
                'value' => $node->getEntityId()
            );
     }
            
            if ($node->hasChildren()) {
                $this->_getChildOptions($node->getChildren());
            }
        }
        return $this->_options;
    }
    /**
     * @param Varien_Data_Tree_Node_Collection $nodeCollection
     */
    protected function _getChildOptions(Varien_Data_Tree_Node_Collection $nodeCollection)
    {
        foreach ($nodeCollection as $node) {
            /* @var $node Varien_Data_Tree_Node */
            $prefix = str_repeat(self::REPEATER, $node->getLevel() * 1) . self::PREFIX_END;
            $this->_options[] = array(
                'label' => $prefix . $node->getName(),
                'value' => $node->getEntityId()
            );
            if ($node->hasChildren()) {
                $this->_getChildOptions($node->getChildren());
            }
        }
    }
}

Step 34: Create file in app/code/community/Vijay/CustomBackground/Model/Resource/Setup.php and add below code in it.

<?php

class Vijay_CustomBackground_Model_Resource_Setup extends Mage_Core_Model_Resource_Setup
{
}

Step 35: Create file in app/code/community/Vijay/CustomBackground/Model/Resource/Background.php and add below code in it.

<?php

class Vijay_CustomBackground_Model_Resource_Background extends Mage_Core_Model_Resource_Db_Abstract
{

    /**
     * constructor
     *
     * @access public
     * @author Ultimate Module Creator
     */
    public function _construct()
    {
        $this->_init('vijay_custombackground/background', 'entity_id');
    }

    /**
     * Get store ids to which specified item is assigned
     *
     * @access public
     * @param int $backgroundId
     * @return array
     * @author Ultimate Module Creator
     */
    public function lookupStoreIds($backgroundId)
    {
        $adapter = $this->_getReadAdapter();
        $select  = $adapter->select()
            ->from($this->getTable('vijay_custombackground/background_store'), 'store_id')
            ->where('background_id = ?', (int)$backgroundId);
        return $adapter->fetchCol($select);
    }

    /**
     * Perform operations after object load
     *
     * @access public
     * @param Mage_Core_Model_Abstract $object
     * @return Vijay_CustomBackground_Model_Resource_Background
     * @author Ultimate Module Creator
     */
    protected function _afterLoad(Mage_Core_Model_Abstract $object)
    {
        if ($object->getId()) {
            $stores = $this->lookupStoreIds($object->getId());
            $object->setData('store_id', $stores);
        }
        return parent::_afterLoad($object);
    }

    /**
     * Retrieve select object for load object data
     *
     * @param string $field
     * @param mixed $value
     * @param Vijay_CustomBackground_Model_Background $object
     * @return Zend_Db_Select
     */
    protected function _getLoadSelect($field, $value, $object)
    {
        $select = parent::_getLoadSelect($field, $value, $object);
        if ($object->getStoreId()) {
            $storeIds = array(Mage_Core_Model_App::ADMIN_STORE_ID, (int)$object->getStoreId());
            $select->join(
                array('custombackground_background_store' => $this->getTable('vijay_custombackground/background_store')),
                $this->getMainTable() . '.entity_id = custombackground_background_store.background_id',
                array()
            )
            ->where('custombackground_background_store.store_id IN (?)', $storeIds)
            ->order('custombackground_background_store.store_id DESC')
            ->limit(1);
        }
        return $select;
    }

    /**
     * Assign background to store views
     *
     * @access protected
     * @param Mage_Core_Model_Abstract $object
     * @return Vijay_CustomBackground_Model_Resource_Background
     * @author Ultimate Module Creator
     */
    protected function _afterSave(Mage_Core_Model_Abstract $object)
    {
        $oldStores = $this->lookupStoreIds($object->getId());
        $newStores = (array)$object->getStores();
        if (empty($newStores)) {
            $newStores = (array)$object->getStoreId();
        }
        $table  = $this->getTable('vijay_custombackground/background_store');
        $insert = array_diff($newStores, $oldStores);
        $delete = array_diff($oldStores, $newStores);
        if ($delete) {
            $where = array(
                'background_id = ?' => (int) $object->getId(),
                'store_id IN (?)' => $delete
            );
            $this->_getWriteAdapter()->delete($table, $where);
        }
        if ($insert) {
            $data = array();
            foreach ($insert as $storeId) {
                $data[] = array(
                    'background_id'  => (int) $object->getId(),
                    'store_id' => (int) $storeId
                );
            }
            $this->_getWriteAdapter()->insertMultiple($table, $data);
        }
        return parent::_afterSave($object);
    }

    /**
     * process multiple select fields
     *
     * @access protected
     * @param Mage_Core_Model_Abstract $object
     * @return Vijay_CustomBackground_Model_Resource_Background
     * @author Ultimate Module Creator
     */
    protected function _beforeSave(Mage_Core_Model_Abstract $object)
    {
        $backgroundtargetid = $object->getBackgroundTargetId();
        if (is_array($backgroundtargetid)) {
            $object->setBackgroundTargetId(implode(',', $backgroundtargetid));
        }
        return parent::_beforeSave($object);
    }
}

Step 36: Create file in app/code/community/Vijay/CustomBackground/Model/Resource/Background/Collection.php and add below code in it.

<?php

class Vijay_CustomBackground_Model_Resource_Background_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
    protected $_joinedFields = array();

    /**
     * constructor
     *
     * @access public
     * @return void
     * @author Ultimate Module Creator
     */
    protected function _construct()
    {
        parent::_construct();
        $this->_init('vijay_custombackground/background');
        $this->_map['fields']['store'] = 'store_table.store_id';
    }

    /**
     * Add filter by store
     *
     * @access public
     * @param int|Mage_Core_Model_Store $store
     * @param bool $withAdmin
     * @return Vijay_CustomBackground_Model_Resource_Background_Collection
     * @author Ultimate Module Creator
     */
    public function addStoreFilter($store, $withAdmin = true)
    {
        if (!isset($this->_joinedFields['store'])) {
            if ($store instanceof Mage_Core_Model_Store) {
                $store = array($store->getId());
            }
            if (!is_array($store)) {
                $store = array($store);
            }
            if ($withAdmin) {
                $store[] = Mage_Core_Model_App::ADMIN_STORE_ID;
            }
            $this->addFilter('store', array('in' => $store), 'public');
            $this->_joinedFields['store'] = true;
        }
        return $this;
    }

    /**
     * Join store relation table if there is store filter
     *
     * @access protected
     * @return Vijay_CustomBackground_Model_Resource_Background_Collection
     * @author Ultimate Module Creator
     */
    protected function _renderFiltersBefore()
    {
        if ($this->getFilter('store')) {
            $this->getSelect()->join(
                array('store_table' => $this->getTable('vijay_custombackground/background_store')),
                'main_table.entity_id = store_table.background_id',
                array()
            )
            ->group('main_table.entity_id');
            /*
             * Allow analytic functions usage because of one field grouping
             */
            $this->_useAnalyticFunction = true;
        }
        return parent::_renderFiltersBefore();
    }

    /**
     * get backgrounds as array
     *
     * @access protected
     * @param string $valueField
     * @param string $labelField
     * @param array $additional
     * @return array
     * @author Ultimate Module Creator
     */
    protected function _toOptionArray($valueField='entity_id', $labelField='background_name', $additional=array())
    {
        return parent::_toOptionArray($valueField, $labelField, $additional);
    }

    /**
     * get options hash
     *
     * @access protected
     * @param string $valueField
     * @param string $labelField
     * @return array
     * @author Ultimate Module Creator
     */
    protected function _toOptionHash($valueField='entity_id', $labelField='background_name')
    {
        return parent::_toOptionHash($valueField, $labelField);
    }

    /**
     * Get SQL for get record count.
     * Extra GROUP BY strip added.
     *
     * @access public
     * @return Varien_Db_Select
     * @author Ultimate Module Creator
     */
    public function getSelectCountSql()
    {
        $countSelect = parent::getSelectCountSql();
        $countSelect->reset(Zend_Db_Select::GROUP);
        return $countSelect;
    }
}

Step 37: Create file in app/code/community/Vijay/CustomBackground/Model/Background.php and add below code in it.

<?php

class Vijay_CustomBackground_Model_Background extends Mage_Core_Model_Abstract
{
    /**
     * Entity code.
     * Can be used as part of method name for entity processing
     */
    const ENTITY    = 'vijay_custombackground_background';
    const CACHE_TAG = 'vijay_custombackground_background';
 
 const TARGET_CMS = 1;
    const TARGET_PRODUCT = 2;
    const TARGET_CATEGORY = 3;
    const TARGET_CUSTOMER = 4;
    const TARGET_HOME = 5;
    const TARGET_CHECKOUT = 6;
    const TARGET_CART = 7;
 const TARGET_OTHER = 8;
    /**
     * Prefix of model events names
     *
     * @var string
     */
    protected $_eventPrefix = 'vijay_custombackground_background';

    /**
     * Parameter name in event
     *
     * @var string
     */
    protected $_eventObject = 'background';

    /**
     * constructor
     *
     * @access public
     * @return void
     * @author Ultimate Module Creator
     */
    public function _construct()
    {
        parent::_construct();
        $this->_init('vijay_custombackground/background');
    }

    /**
     * before save background
     *
     * @access protected
     * @return Vijay_CustomBackground_Model_Background
     * @author Ultimate Module Creator
     */
    protected function _beforeSave()
    {
        parent::_beforeSave();
        $now = Mage::getSingleton('core/date')->gmtDate();
        if ($this->isObjectNew()) {
            $this->setCreatedAt($now);
        }
        $this->setUpdatedAt($now);
        return $this;
    }

    /**
     * save background relation
     *
     * @access public
     * @return Vijay_CustomBackground_Model_Background
     * @author Ultimate Module Creator
     */
    protected function _afterSave()
    {
        return parent::_afterSave();
    }

    /**
     * get default values
     *
     * @access public
     * @return array
     * @author Ultimate Module Creator
     */
    public function getDefaultValues()
    {
        $values = array();
        $values['status'] = 1;
        return $values;
    }
    
    /**
      * get Background Target Page
      *
      * @access public
      * @return array
      * @author Ultimate Module Creator
      */
    public function getBackgroundTargetId()
    {
        if (!$this->getData('background_target_id')) {
            return explode(',', $this->getData('background_target_id'));
        }
        return $this->getData('background_target_id');
    }
}

Step 38: Create file in app/design/adminhtml/default/default/layout/vijay_custombackground.xml and add below code in it.

<?xml version="1.0"?>

         
     
       
                        
                
       
                        
                
                
                        
                
                
                 
                
                
                        vijaycustombackgroundimage/style.css
                
              
    
    
        
            
                vijay_custombackground/background
            
        
        
            

        
    
    
        
            
        
    
    
    
        
        
            jsjscolor/jscolor.js
        
        
            
                vijay_custombackground/background
            
        
        
            
        
        
            
        
    



Step 39: Create file in app/design/frontend/base/default/layout/vijay_custombackground.xml and add below code in it.

<?xml version="1.0"?>

    
        
            
        
    


Step 40: Create file in app/design/frontend/base/default/template/vijay/custombackground/js.phtml and add below code in it.

<?php if ($this->canShow()): ?>
 <?php if($this->isBackgroundNeeded()): ?>
  <script>
   if($$('<?php echo $this->getTargetElement() ?>').length>0){
    $$('<?php echo $this->getTargetElement() ?>').each(function(element){
     <?php foreach($this->getStyleOptions() as $style => $value): ?>
                    element.setStyle({<?php echo $style ?>: '<?php echo $value ?>'});
                 <?php endforeach ?>
    })
   }
  </script>
 <?php endif ?>
<?php endif; ?>

Step 41: Add JS files in js/vijaycustombackgroundimage folder. You can download JS files from https://github.com/vijayrami/Storewise_Custombackground_for_Pages/tree/master/js/vijaycustombackgroundimage

Step 42: Add CSS files in skin/adminhtml/default/default/vijaycustombackgroundimage folder. You can download CSS files from https://github.com/vijayrami/Storewise_Custombackground_for_Pages/tree/master/skin/adminhtml/default/default/vijaycustombackgroundimage

Step 43: Add Language Translation file. Create file in app/locale/en_US/Vijay_CustomBackground.csv. You can download this file from
https://github.com/vijayrami/Storewise_Custombackground_for_Pages/tree/master/app/locale/en_US
Tag : Magento
0 Comments On "Add Store wise Custom Background Image For Different Pages In Magento"

Back To Top