December 05, 2012

December 05, 2012
11
In this article, we are going to discuss about How to add custom table to the magento product admin. In Magento, it is possible to add new attributes to each product models and edit the values for these attributes on the Product Edit Page. This article provide a facility for processing that data when the user hits the Save button.

Step 1:
Create the extension's setup file, which loads the extension into Magento. Add the below code in app/etc/modules/Phpcmsframework_Customtabs.xml

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

This file will register the extension in Magento, telling it to look in the app/code/local/Phpcmsframework/Customtabs/ directory for the extension's code.

Step 2:

The next file we make is the extension's config file. This file is a more detailed setup file, containing information about the extension's classes, layout files and everything else we need to make it work.

Notice the events section of this file (below)? To save the product data, we listen for an event that is triggered when ever a product is saved in the Magento Admin. This allows us to access the custom data we have created in the tab and process/save it.

Add the below code in app/code/local/Phpcmsframework/Customtabs/etc/config.xml

<?xml version="1.0"?>
<config>
    <modules>
        <Phpcmsframework_CustomTabs>
            <version>0.1.0</version>
        </Phpcmsframework_CustomTabs>
    </modules>
    <global>
        <blocks>
            <customtabs>
                <class>Phpcmsframework_Customtabs_Block</class>
            </customtabs>
        </blocks>
        <models>
            <customtabs>
                <class>Phpcmsframework_Customtabs_Model</class>
            </customtabs>
        </models>
    </global>
    <adminhtml>
        <layout>
            <updates>
                <customtabs>
                    <file>customtabs.xml</file>
                </customtabs>
            </updates>
        </layout>
        <events>
            <catalog_product_save_after>
                <observers>
                    <Phpcmsframework_save_product_data>
                        <type>singleton</type>
                        <class>customtabs/observer</class>
                        <method>saveProductTabData</method>
                    </Phpcmsframework_save_product_data>
                </observers>
            </catalog_product_save_after>
        </events>
    </adminhtml>
</config>

Step 3:
Add the below code in app/code/local/Phpcmsframework/Customtabs/Block/Adminhtml/Catalog/Product/Tab.php


<?php

class Phpcmsframework_Customtabs_Block_Adminhtml_Catalog_Product_Tab 
extends Mage_Adminhtml_Block_Template
implements Mage_Adminhtml_Block_Widget_Tab_Interface {

    /**
     * Set the template for the block
     *
     */
    public function _construct()
    {
        parent::_construct();
         
        $this->setTemplate('customtabs/catalog/product/tab.phtml');
    }
     
    /**
     * Retrieve the label used for the tab relating to this block
     *
     * @return string
     */
    public function getTabLabel()
    {
        return $this->__('My Custom Tab');
    }
     
    /**
     * Retrieve the title used by this tab
     *
     * @return string
     */
    public function getTabTitle()
    {
        return $this->__('Click here to view your custom tab content');
    }
     
    /**
     * Determines whether to display the tab
     * Add logic here to decide whether you want the tab to display
     *
     * @return bool
     */
    public function canShowTab()
    {
        return true;
    }
     
    /**
     * Stops the tab being hidden
     *
     * @return bool
     */
    public function isHidden()
    {
        return false;
    }

    /**
     * AJAX TAB's
     * If you want to use an AJAX tab, uncomment the following functions
     * Please note that you will need to setup a controller to recieve
     * the tab content request
     *
     */
    /**
     * Retrieve the class name of the tab
     * Return 'ajax' here if you want the tab to be loaded via Ajax
     *
     * return string
     */
#   public function getTabClass()
#   {
#       return 'my-custom-tab';
#   }

    /**
     * Determine whether to generate content on load or via AJAX
     * If true, the tab's content won't be loaded until the tab is clicked
     * You will need to setup a controller to handle the tab request
     *
     * @return bool
     */
#   public function getSkipGenerateContent()
#   {
#       return false;
#   }

    /**
     * Retrieve the URL used to load the tab content
     * Return the URL here used to load the content by Ajax 
     * see self::getSkipGenerateContent & self::getTabClass
     *
     * @return string
     */
#   public function getTabUrl()
#   {
#       return null;
#   }
 }

Step 4:
This is the layout file for the Adminhtml section of the extension. In here we will include the tab on the Magento Product edit page.


Add the below xml code in, app/design/adminhtml/default/default/layout/customtabs.xml

<?xml version="1.0"?>
<layout>
    <adminhtml_catalog_product_edit>
        <reference name="product_tabs">
            <action method="addTab">
                <name>my_custom_tab</name>
                <block>customtabs/adminhtml_catalog_product_tab</block>
            </action>
        </reference>
    </adminhtml_catalog_product_edit>
</layout>

Step 5:
This file is quite simple but without it, nothing will show on the product edit page. The last thing to do before we can see our tab in action is to create our new template file.

Add the below code in, app/design/adminhtml/default/default/template/customtabs/catalog/product/tab.phtml


<?php
/**
 * Custom tab template
 */
?>
<div class="input-field">
 <label for="custom_field">Custom Field</label>
 <input type="text" class="input-text" name="custom_field" id="custom_field" />
</div>

Step 6:
Testing Our Custom Magento Admin Tab

Now that we have the code in place, let's refresh our cache, go to a product edit page and see the tab in action!

Did it work? If it didn't work, check through your XML again as a slight error in any of that will stop everything working.

Now that we have our tab, let's take a look at how to process the data once the user hits the 'Save' button.

Step 7:
Saving our Custom Tab Data

To access the data during the saving process, we have hooked into an event called catalog_product_save_after (see config.xml above). This event is triggered each time a product model is saved. As we have declared our observer for this event inside the adminhtml block, we will only trigger our code when a product model is saved from the Magento Admin.

app/code/local/Phpcmsframework/Customtabs/Model/Observer.php

<?php
  
class Phpcmsframework_Customtabs_Model_Observer
{
    /**
     * Flag to stop observer executing more than once
     *
     * @var static bool
     */
    static protected $_singletonFlag = false;

    /**
     * This method will run when the product is saved from the Magento Admin
     * Use this function to update the product model, process the 
     * data or anything you like
     *
     * @param Varien_Event_Observer $observer
     */
    public function saveProductTabData(Varien_Event_Observer $observer)
    {
        if (!self::$_singletonFlag) {
            self::$_singletonFlag = true;
             
            $product = $observer->getEvent()->getProduct();
         
            try {
                /**
                 * Perform any actions you want here
                 *
                 */
                $customFieldValue =  $this->_getRequest()->getPost('custom_field');

                /**
                 * Uncomment the line below to save the product
                 *
                 */
                //$product->save();
            }
            catch (Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
            }
        }
    }
      
    /**
     * Retrieve the product model
     *
     * @return Mage_Catalog_Model_Product $product
     */
    public function getProduct()
    {
        return Mage::registry('product');
    }
     
    /**
     * Shortcut to getRequest
     *
     */
    protected function _getRequest()
    {
        return Mage::app()->getRequest();
    }
}

11 comments:

  1. Hi, it works but how the saved value isn't showing in the textfield? Also, how do we retrieve in frontend?

    ReplyDelete
  2. Hello, I see the custom tab in the product edit screen.
    I added the code for Observer.php, but when saving the data the url is redirected to "../index.php/admin/catalog_product/save/store/0/id/432/key/"

    ReplyDelete
  3. When I use the "catalog_product_prepare_save" event as suggested by niaxilin it works as I expected!

    The screen goes back to the product list or product when I select save and continue.

    ReplyDelete
  4. This did worked but in a reverse manner, actually I was looking for something to which I can remove custom tabs, with little modification I was able to do that.

    ReplyDelete
  5. There are dozens of Magento extension maintainers at present, who provide Magento’s varied users a chance to optimize or customize their Magento to avail the best of its performance. As each maintainer has its own methodology of tweaking the code, sometimes integrating modules from more than one maintainer may result in a clash and manipulating your stable environment. More often than not the consequences may be so high that you might want to start everything from scratch.

    Magento Hosting I Magento Cloud Hosting

    ReplyDelete
  6. Hi ..

    I had facing in product grid page in admin panel.
    Here i follow your instruction to create admin product extra tabs.but it doesnt working for me..I thoroughly check my xml file .i can`t find what my mistake,

    ReplyDelete
  7. I've got it working except for the save part. When I save my product the text field disappears when I view the product again. Any guidance would be much appreciated.

    ReplyDelete
  8. Mage registry key "_singleton/customtabs/observer" already exists error occur and data will cant save.

    ReplyDelete
  9. I can see the tab but the custom field is not being saved. please help!!

    ReplyDelete
  10. I want to use this custom tab for file upload function after create the tab where I insert the file upload code

    ReplyDelete