Pankaj Pareek
Pankaj Pareek

Reputation: 3836

How to show Sum of Two fields in Grid in Magento Admin Panel

I am working on a extension in which user enter different price for " Stamp Cost, Ink Cost, Form Cost ". currently in data grid i am showing value of one field

$this->addColumn('stamp_cost', array(
    'header'    => Mage::helper('imprint')->__('Stamp Cost'),
    'width'     => '100px',
    'type'  => 'price',
    'currency_code' => $store->getBaseCurrency()->getCode(),
    'index'     => 'stamp_cost'
));

But Now I Need to show sum of all these fields in one column

How can we show sum of two fields in one column in magento admin data grid ?

Upvotes: 3

Views: 4675

Answers (2)

xvrmallafre
xvrmallafre

Reputation: 1

The more right way is 'renderer' => 'company_module/adminhtml_renderer_costSum'

As @Zyava says, the correct option is this. But actually, is not 'company_module'. Instead you should call it as you have declared your blocks in the config.xml file.

<blocks>
    <declaration>
        <class>Company_Module_Block</class>
    </declaration>
</blocks>

So, in this case you should create the 'renderer' as:

'renderer' => 'declaration/adminhtml_renderer_costSum'

Upvotes: 0

Max
Max

Reputation: 8836

Essentially, there are two ways to do it. Add the field to the collection and get the data from the database, or calculate it in PHP based on the 3 values returned from the DB. Doing the first way with the Magento Collection would, in my opinion, be too complex. instead, you want to use a Renderer (Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract)

First, inside of the Block/Adminhtml folder of your plugin, make a new folder called Renderer. Inside of it make a new file called CostSum.php with the following contents:

<?php 
class Company_Module_Block_Adminhtml_Renderer_CostSum extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
{
    public function render(Varien_Object $row)
    {
         return $row->getStampCost() + $row->getInkCost() + $row->getFormCost();
    }
}

Then, in the grid, make a new column

$this->addColumn('cost_total', array(
    'header'    => Mage::helper('imprint')->__('Stamp Cost'),
    //'index'     => 'Im not sure this is necessary',
    'type'      => 'price',
    'currency_code' => $store->getBaseCurrency()->getCode(),
    'renderer' => new Company_Module_Block_Adminhtml_Renderer_CostSum() 
));

Hope that helps!

Upvotes: 3

Related Questions