Hey guys,

It’s such a long time since our last meeting on our Magento Tutorial section, isn’t it?

Today, we will continue with lesson 8 (Advanced magento grid) in our Magento Tutorial which includes 3 main parts:

1. Mass action in Magento grid
2. Display types in Magento grid
a. Supported-by-Magento types
b. Unsupported-by-Magento types
3. Data exporting to csv/xml in Magento grid

1. Mass action in magento grid

a. Benefit of mass action

Working with many rows at the same time without having to view each row in detail.

Magento Open course-Advanced magento grid-Mass action

b. Steps to create mass action for magento grid

  • Step 1: write the function _prepareMassaction() in the file block grid

Example Code: app\code\local\Magestore\Lesson08\Block\Adminhtml\Lesson08\Grid.php

**
* prepare mass action for this grid
*
* @return Magestore_Lesson08_Block_Adminhtml_Lesson08_Grid
*/
protected function _prepareMassaction()
{
$this->setMassactionIdField('lesson08_id');
$this->getMassactionBlock()->setFormFieldName('lesson08');
$this->getMassactionBlock()->addItem('delete', array(
'label' => Mage::helper('lesson08')->__('Delete'),
'url' => $this->getUrl('*/*/massDelete'),
'confirm' => Mage::helper('lesson08')->__('Are you sure?')
));

$statuses = Mage::getSingleton('lesson08/status')->getOptionArray();

array_unshift($statuses, array('label'=>'', 'value'=>''));
$this->getMassactionBlock()->addItem('status', array(
'label'=> Mage::helper('lesson08')->__('Change status'),
'url' => $this->getUrl('*/*/massStatus', array('_current'=>true)),
'additional' => array(
'visibility' => array(
'name' => 'status',
'type' => 'select',
'class' => 'required-entry',
'label' => Mage::helper('lesson08')->__('Status'),
'values'=> $statuses
))
));
return $this;
}

setMassactionIdField: set id field for mass action

setFormFieldName: set name for the field of posting data

In the example:

$this->getMassactionBlock()->setFormFieldName(‘lesson08’);

The System will post an Id array with the name of ‘lesson08’.

addItem: add 1 mass action

/ /**
* Add new massaction item
*
* $item = array(
* 'label' => string,
* 'complete' => string, // Only for ajax enabled grid (optional)
* 'url' => string,
* 'confirm' => string, // text of confirmation of this action (optional)
* 'additional' => string|array|Mage_Core_Block_Abstract // (optional)
* );
*
* @param string $itemId
* @param array $item
* @return Mage_Adminhtml_Block_Widget_Grid_Massaction_Abstract
*/
public function addItem($itemId, array $item)
{
$this->_items[$itemId] = $this->getLayout()->createBlock('adminhtml/widget_grid_massaction_item')
->setData($item)
->setMassaction($this)
->setId($itemId);

if($this->_items[$itemId]->getAdditional()) {
$this->_items[$itemId]->setAdditionalActionBlock($this->_items[$itemId]->getAdditional());
$this->_items[$itemId]->unsAdditional();
}

return $this;
}

In this example, we have just added 2 mass actions which are:

massDelete: to delete a list of rows

massStatus: to change status of many rows at the same time

  • Step 2: write action in the file controller to carry out this action

Example Code: app\code\local\Magestore\Lesson08\controllers\Adminhtml\Lesson08Controller.php

Mass Delete

public function massDeleteAction()
{
$lesson08Ids = $this->getRequest()->getParam('lesson08');
if (!is_array($lesson08Ids)) {
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('adminhtml')->__('Please select item(s)'));
} else {
try {
foreach ($lesson08Ids as $lesson08Id) {
$lesson08 = Mage::getModel('lesson08/lesson08')->load($lesson08Id);
$lesson08->delete();
}
Mage::getSingleton('adminhtml/session')->addSuccess(
Mage::helper('adminhtml')->__('Total of %d record(s) were successfully deleted',
count($lesson08Ids))
);
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
}
}
$this->_redirect('*/*/index');
}

Mass change status

public function massStatusAction()
{
$lesson08Ids = $this->getRequest()->getParam('lesson08');
if (!is_array($lesson08Ids)) {
Mage::getSingleton('adminhtml/session')->addError($this->__('Please select item(s)'));
} else {
try {
foreach ($lesson08Ids as $lesson08Id) {
Mage::getSingleton('lesson08/lesson08')
->load($lesson08Id)
->setStatus($this->getRequest()->getParam('status'))
->setIsMassupdate(true)
->save();
}
$this->_getSession()->addSuccess(
$this->__('Total of %d record(s) were successfully updated', count($lesson08Ids))
);
} catch (Exception $e) {
$this->_getSession()->addError($e->getMessage());
}
}
$this->_redirect('*/*/index');
}

2. Display types in magento grid

Example Code: app\code\local\Magestore\Lesson08\Block\Adminhtml\Lesson08\Grid.php

By default, Magento supports many displaying types for data in grid such as number, text, date, currency, options…But in this Advanced magento grid lesson, we only mention the most popular ones:

a. Supported-by-Magento types

Date

Magento open course-Advanced magento grid-Date

Renderer class: adminhtml/widget_grid_column_renderer_date

For example,

$this->addColumn('date_field', array(
'header' => Mage::helper('lesson08')->__('Date'),
'width' => '150px',
'index' => 'date_field',
'type' => 'date',
'format' => Mage::app()->getLocale()->getDateFormat(Mage_Core_Model_Locale::FORMAT_TYPE_MEDIUM)
));

Some date format types:

  • Mage_Core_Model_Locale::FORMAT_TYPE_MEDIUM

Normal display

For example, Aug 30, 2013

  • Mage_Core_Model_Locale::FORMAT_TYPE_SHORT

Short display

For example, 8/30/13

  • Mage_Core_Model_Locale::FORMAT_TYPE_LONG

Full display

For example, August 30, 2013

Number

Magento open course-Advanced magento grid

Renderer class: adminhtml/widget_grid_column_renderer_number

For example,

 $this->addColumn('number_field', array(
'header' => Mage::helper('lesson08')->__('Number'),
'width' => '150px',
'index' => 'number_field',
'type' => 'number'
));

Price

Magento open course-Advanced magento grid-price

Renderer class: adminhtml/widget_grid_column_renderer_price

For example,

$this->addColumn('price_field', array(
'header' => Mage::helper('lesson08')->__('Price'),
'width' => '150px',
'index' => 'price_field',
'type' => 'price'
));

Options

Magento open course-Advanced magento grid-options

Renderer class: adminhtml/widget_grid_column_renderer_options

For example,

$this->addColumn('select_field', array(
'header' => Mage::helper('lesson08')->__('Options'),
'align' => 'left',
'width' => '80px',
'index' => 'status',
'type' => 'options',
'options' => array(
1 => 'Enabled',
2 => 'Disabled',
),
));

Besides, there are many other display types such as Country, Concat, Currency, Action, Checkbox, Datetime, Radio, Input, Select, Text, Store.

 

b. Unsupported-by-Magento types (Custom)

In reality, there are many display types which have not been supported by Magento but still need to be shown such as images, email, etc. In those cases, we will use renderer to add a new row whose display type can be adaptable (for example, sometimes it will be displayed as number, some other times, it will be shown as text, etc ).

There is a simple way to solve the above problem that is to create a class inheriting from the class Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract , rewrite the render method for this new block and declare custom renderer in the method _prepareColumns() for the rendered fields.

advanced magento grid-export data from magento grid to XML files

In this example, we will create a field displaying image.

Example Code: app\code\local\Magestore\Lesson08\Block\Adminhtml\Lesson08\Grid.php

  • Step 1: declares renderer for the field in the method _prepareColumns()
$this->addColumn('filename', array(
'header' => Mage::helper('lesson08')->__('Image'),
'width' => '150px',
'index' => filename',
'renderer' => 'lesson08/adminhtml_lesson08_renderer_image'
));
  • Step 2: Create class renderer inheriting from the class Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
  • Step 3: Write render function for the class that has just been created. Example Code: app\code\local\Magestore\Lesson08\Block\Adminhtml\Lesson08\Renderer\Image.php
class Magestore_Lesson08_Block_Adminhtml_Lesson08_Renderer_Image extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract {

public function render(Varien_Object $row) {
$value = $row->getData($this->getColumn()->getIndex());
return '<img width="150" src="' . Mage::getBaseUrl('media').'lesson08/'.$value . '" />';
}

}

3. Export data from magento grid to CSV/ XML files

Example Code: app\code\local\Magestore\Lesson08\Block\Adminhtml\Lesson08\Grid.php

This function helps export data from magento grid to CSV/XML files so as to print or import them into other accounting system.

Advanced magento grid-Export data from magento grid to CSV/XML files

– The first step is to add the box “select” and button “export” to the grid through the function _prepareColumns()

$this->addExportType('*/*/exportCsv', Mage::helper('lesson08')->__('CSV'));
$this->addExportType('*/*/exportXml', Mage::helper('lesson08')->__('XML'));

In the function addExportType:

  • 1st parameter: action to process export data

For example, ‘*/*/exportCsv’

In this example, the action to process export data to CSV is exportCsv in the controller file app\code\local\Magestore\Lesson08\controllers\Adminhtml\Lesson08Controller.php

  • 2nd parameter: label of export type

For example, Mage::helper(‘lesson08’)->__(‘CSV’)

This label will be displayed in the select box of export

Advanced magento grid-Export data from magento grid to CSV/XML files

– The second step is to write action for each type in the controller file

Example Code

app\code\local\Magestore\Lesson08\controllers\Adminhtml\Lesson08Controller.php

public function exportCsvAction()
{
$fileName = 'lesson08.csv';
$content = $this->getLayout()
->createBlock('lesson08/adminhtml_lesson08_grid')
->getCsv();
$this->_prepareDownloadResponse($fileName, $content);
}

In this example, after exporting to CSV, we get a file as below:

"ID","Text","Date","Number","Price","Options"
"1","Text 01","Aug 7, 2013","231","$322.43","Enabled"
"2","Text 02","Aug 30, 2013","4566","$22.67","Enabled"

Steps to export data from magento grid to CSV/XML files brings us to the end of this lesson. Hope “Advanced Magento Grid” session is useful for you. Follow us in Magento Open Course for Magento Tutorial.

Author

Why Magestore? We believe in building a meaningful & long-term relationship with you.

Write A Comment