Magento – Adding a column to export but hiding from the grid

adminhtmlexportgridreports

I've created a custom report. The report has a significant number of fields in it which are required for when it's exported in CSV form.

What I'm trying to figure out is if there's a way to omit the rendering of some of the fields on the front-end grid. Most of them aren't really important for the filtering process in admin and are only used when the report is downloaded for further parsing outside of Magento.

I would expect this to type of functionality to reside in the grid class as that's what generates the actual grid and, later on, the exported CSV but I don't see anything that looks like it deals with visibility.

Before I go in and override methods in this class for our custom report, is there a lesser-known way to accomplish this that's easier than my adding some kind of "showInGrid" property via the addColumn property array?

TL,DR is there an easy way to have fields exported (in say, CSV or
XML) but omitted from the admin grid?

Best Answer

Create a separate block definition - e.g. duplicate the Grid block to another block that's specific for your CSV; I would call this Csvgrid.php instead of Grid.php - it would contain all of the same functionality that the normal Grid.php contains, but omit the one column.

In your controller:

public function exportCsvAction()
{
        $fileName = 'myreport_'.date('Y_m_d_h_i_s').'.csv';
        $content = $this->getLayout()->createBlock('mymodule/adminhtml_reports_csvgrid')->getCsv();
}

When duplicating the Grid, place Csvgrid.php into the same physical directory as Grid.php but rename it accordingly - don't forget to change the class name!

Edit:

So it turns out that Mage_Adminhtml_Block_Widget_Grid has a method called removeColumn - defined as:

/

**
     * Remove existing column
     *
     * @param string $columnId
     * @return Mage_Adminhtml_Block_Widget_Grid
     */
    public function removeColumn($columnId)
    {
        if (isset($this->_columns[$columnId])) {
            unset($this->_columns[$columnId]);
            if ($this->_lastColumnId == $columnId) {
                $this->_lastColumnId = key($this->_columns);
            }
        }
        return $this;
    }

My guess is that because Mage_Adminhtml_Block_Report_Grid extends Mage_Adminhtml_Block_Widget_Grid it inherits this method and should be able to be used. I would, in that case, create a new block Grid and extend the Grid that your current report is in. From there you can use your own prepareColumns method, call the parent::_prepareColumns() and then call removeColumn..

Best of luck.

Related Topic