Aug 23, 2011

Magento: Exporting button on your data in a grid.


Adding Export button


In your Grid class(Package_Module_Block_Grid), find the method named _prepareColumns and add the code below.
$this->addExportType('*/*/exportCsv', Mage::helper('download')->__('CSV'));
$this->addExportType('*/*/exportXml', Mage::helper('download')->__('XML'));


Implement Export method/Action


In your action controller class (Package_Module_Adminhtml_DownloadController) create two methods.

class Globe_Download_Adminhtml_DownloadController extends Mage_Adminhtml_Controller_Action{

public function exportXmlAction() {
}
public function exportCvsAction() {
}
protected function _prepareDownloadResponse($fileName, $content, $contentType = 'application/octet-stream', $contentLength = null)
{
$session = Mage::getSingleton('admin/session');
if ($session->isFirstPageAfterLogin()) {
$this->_redirect($session->getUser()->getStartupPageUrl());
return $this;
}
$this->getResponse()
->setHttpResponseCode(200)
->setHeader('Pragma', 'public', true)
->setHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0', true)
->setHeader('Content-type', $contentType, true)
->setHeader('Content-Length', is_null($contentLength) ? strlen($content) : $contentLength)
->setHeader('Content-Disposition', 'attachment; filename=' . $fileName)
->setHeader('Last-Modified', date('r'))
->sendHeaders(); // Need to call this method after all you send the Headers.
if (!is_null($content)) {
$this->getResponse()->setBody($content);
}
return $this;
}

}



Thanks to the other author for sharing what they knows about magento development. In this post I only put the part of the code that I understand or I use it in my application.


Rerefences:
  • http://subesh.com.np/2010/03/create-download-xls-report-file-magentos-core/
  • http://www.webspeaks.in/2010/08/create-admin-backend-module-in-magento.html

No comments: