Grid Column Options

Posted Over 8 years ago. Visible to the public.

Column Types

Take a look at Mage_Adminhtml_Block_Widget_Grid_Column::_getRendererByType() to dive into the different column types:

app\code\core\Mage\Adminhtml\Block\Widget\Grid\Column\Renderer\Abstract.php

  1. date
  2. datetime
  3. number
  4. currency
  5. price
  6. country
  7. concat
  8. action
  9. options
  10. checkbox
  11. massaction
  12. radio
  13. input
  14. select
  15. text
  16. store
  17. wrapline
  18. theme

Code Snippets

Checkbox

See app\code\core\Mage\Adminhtml\Block\Widget\Grid\Column\Renderer\Checkbox.php.

    protected function _prepareColumns()
    {
        $this->addColumn('apply_to_product', [
            'header_css_class' => 'a-center',
            'type'      => 'checkbox',
            'name'      => 'apply_to_product',
            'field_name' => 'selected_products[]',
            'values'    => $this->_getSelectedProducts(),
            'align'     => 'center',
            'index'     => 'product_id'
        ]);
    }

    protected function _getSelectedProducts()
    {
        return $this->getRequest()->getPost('selected_products', []);
    }

    /**
     * Retrieve AJAX URL for grid when filtering or resetting 
     *
     * @return string
     */
    public function getGridUrl()
    {
        return $this->getUrl('*/*/product', ['_current'=>true]);
    }

Currency

        // Specify the currency code.
        $this->addColumn('unit_price', [
            'header'    => $helper->__('Unit Price'),
            'index'     => 'unit_price',
            'width'     => '80px',
            'sortable'  => false,
            'filter'    => false,
            'type'  => 'currency',
            'currency_code' => 'MYR',
        ]);
        
        // Currency code is specified in another column.
        $this->addColumn('billing_amount', [
            'header' => $helper->__('Billing Amount'),
            'index' => 'billing_amount',
            'type'  => 'currency',
            'currency' => 'billing_currency_code',
        ]);

Date Time

        $this->addColumn('created_at', [
            'header'    => $helper->__('Requested At'),
            'index'     => 'created_at',
            'type'      => 'datetime',
            'width'     => '100px',
            'align'     => 'center',
            'filter_index' => 'main_table.created_at',
            'gmtoffset' => true
        ]);
        
       $this->addColumn('pickup_at', [
            'header'    => $helper)->__('Pickup At'),
            'width'     => '80px',            
            'index'     => 'pickup_at',
            'start_time'=> 'o_created_at', //order creaton time
            'cond'      => 'order_lot_id', //condition: if !order_lot_id then return ''
            'format'    => 'h:m:s a',
            'renderer'  => 'patron/adminhtml_order_grid_renderer_duration',
            'filter'    => false,
            'sort'      => false
        ]);
        
        $this->addColumn('to_deliver_at', [
            'header'    => $helper->__('To Deliver At'),
            'width'     => '80px',            
            'index'     => 'to_deliver_at',
            'start_time'=> 'o_created_at', //order creaton time
            'cond'      => 'order_id', //condition: if !order_id then return ''
            'format'    => 'h:m:s a',
            'renderer'  => 'patron/adminhtml_order_grid_renderer_duration',
            'filter'    => false,
            'sort'      => false
        ]);

Action Column

        $this->addColumn('action', [
            'header'    =>  $helper->__('Action'),
            'width'     => '50px',
            'type'      => 'action',
            'getter'    => 'getCompanyId', // Only one possible getter for row.
            'actions'   => [ // Can fit multiple actions.
                [
                    'caption' => $helper->__('Utilization'),
                    'popup' => true, // Popup new browser window.
                    'url' => [
                        'base' => '*/*/utilization',
                        'params' => [
                            'member_id' => $this->getMemberId(),
                            //'plan_id => $row->getPlanId(), // No can do!
                        ]
                    ],
                    'field'   => 'company_id' // Merge to params: 'company_id' => $row->getCompanyId()                ]
            ],
            'filter'    => false,
            'sortable'  => false,
        ]);

Use callback to construct the URL:

        $this->addColumn('action', [
            'header'    =>  $helper->__('Action'),
            'width'     => '50px',
            'type'      => 'action',
            'getter'    => [$this, 'getFilterParams'],
            'actions'   => [
                [
                    'caption' => $helper->__('Utilization'),
                    'popup' => true,
                    'url' => ['base' => '*/utilization'],
                    'field'   => 'filter'
                ]
            ],
            'filter'    => false,
            'sortable'  => false,
        ]);

        return parent::_prepareColumns();
    }

    /**
     *
     * @param Varien_Object $row
     * @return string
     */
    public function getFilterParams(Varien_Object $row)
    {
        $params = "company={$row->getCompanyId()}&member_id={$this->getMemberId()}&plan={$row->getPlanId()}";
        return Mage::helper('core/string')->urlEncode($params);
    }

Misc

        $this->addColumn('entity_id', array(
            'header'    => Mage::helper('moe')->__('Med#'),
            'width'     => '30px',
            'index'     => 'entity_id',
            'filter_index'=>'main_table.entity_id'
        ));
        $this->addColumn('amount', [
            'header'=> $helper->__('Amount'),
            'width' => '80px',
            'index' => 'amount',
            'type'  => 'number'
        ]);
        $this->addColumn('response_body', array(
            'header'    => Mage::helper('moe')->__('Response Body'),
            'index'     => 'response_body',
            'sortable'  => false,
            'filter'    => false,
            'type'      => 'text', // uses 'adminhtml/widget_grid_column_renderer_longtext'
            'truncate'  => 420,
            'frame_callback' => array($this, 'extractData'),
            'noescape'  => false
        ));

        $this->addColumn('enabled', array(
            'header'    => Mage::helper('moe')->__('Enabled'),
            'align'     => 'left',
            'width'     => '60px',
            'index'     => 'enabled',
            'type'      => 'options',
            'options'   => array(
                1 => Mage::helper('moe')->__('Yes'),
                0 => Mage::helper('moe')->__('No')
            ),
        $this->addColumn('amount', array(
            'header'    => Mage::helper('accountpayment')->__('Amount'),
            'type'      => 'currency',
            'currency'  => 'currency_code',
            'width'     => 80,
            'index'     => 'amount'
        ));
        $options = Mage::getSingleton('sales/order_config')->getStatuses();
        $options['require_correction_follow_up'] = $this->__('Follow up for required correction');
        $this->addColumn('status', array(
            'header' => Mage::helper('sales')->__('Status'),
            'index' => 'status',
            'type'  => 'options',
            'width' => '200px',
            'filter'=> 'adminhtml/widget_grid_column_filter_text',
            'options' => $options,
            'filter_condition_callback' => array($this, '_statusFilter')
        )); 
        
        // ref: Mage_Adminhtml_Block_Catalog_Category_Tab_Product
        $this->addColumn('crosslink', array(
            'header_css_class' => 'a-center',
            'type'      => 'checkbox',
            'name'      => 'crosslink',
            'values'    => $this->_crosslinkStundetIds,
            'align'     => 'center',
            'index'     => 'entity_id'
        ));
        $this->addColumn('country_id', array(
            'header'    => Mage::helper('swms')->__('Country'),
            'index'     => 'country_id',
            'width'     => '100',
            'type'      => 'country',
        ));
        

Custom Renderers

There are 2 ways to custom render the grid's cell, using a class and using a callback.

// Define param 'renderer' => 'patron/adminhtml_order_grid_renderer_duration in addColumn()
class Sxxxxx_Patron_Block_Adminhtml_Order_Grid_Renderer_Duration extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Datetime
{
    public function render(Varien_Object $row)
    {
        $col = $this->getColumn();
        //if no order lot, can't pickup
        if (!$row->getData($col->getCond())) {
            return '';
        }
        $time2 = $row->getData($col->getIndex()); //UTC
        $time1 = strtotime($row->getData($col->getStartTime()));        
        if ($time2) {
            $strRender = parent::render($row);
            $minutes = round((strtotime($time2) - $time1)/60, 0);
            $strRender .= " <$minutes>";
        } else {
            $minutes = round((time() - $time1)/60, 0);
            $strRender = "<$minutes>";
        }        
        return $strRender;
    }
}

Callback within the grid class:

        // ...
        $this->addColumn('admin_updated_at', array(
            'header'    => Mage::helper('module')->__('Updated At'),
            'index'     => 'admin_created_at',
            'type'      => 'datetime',
            'frame_callback' => [$this, 'decorateUserUpdatedAt'],
        ));
        //...
        
    /**
     * @param string $value
     * @param Varien_Object $row
     * @param Mage_Adminhtml_Block_Widget_Grid_Column $column
     * @param bool $isExport
     * @return string
     */
    public function decorateUserUpdatedAt($value, $row, $column, $isExport)
    {
        if (!$isExport && $value > $row->getAdminUpdatedAt()) {
            $cell = '<strong><span class="not-available">' . $value . '</span></strong>';
        } else {
            $cell = $value;
        }
        return $cell;
    }

Column attribute escape, set to false to not escape HTML.

class Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Longtext
    extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
{
    /**
     * Render contents as a long text
     *
     * Text will be truncated as specified in string_limit, truncate or 250 by default
     * Also it can be html-escaped and nl2br()
     *
     * @param Varien_Object $row
     * @return string
     */
    public function render(Varien_Object $row)
    {
        $truncateLength = 250;
        // stringLength() is for legacy purposes
        if ($this->getColumn()->getStringLimit()) {
            $truncateLength = $this->getColumn()->getStringLimit();
        }
        if ($this->getColumn()->getTruncate()) {
            $truncateLength = $this->getColumn()->getTruncate();
        }
        $text = Mage::helper('core/string')->truncate(parent::_getValue($row), $truncateLength);
        if ($this->getColumn()->getEscape() !== FALSE) {
            $text = $this->escapeHtml($text);
        }
        if ($this->getColumn()->getNl2br()) {
            $text = nl2br($text);
        }
        return $text;
    }
}

Add additional js

    /**
     * Convert the status dropdown for filtering to autocompleter   
     */         
    public function getAdditionalJavaScript()
    {      
        return $this->getLayout()
            ->createBlock('****/adminhtml_widget_grid_column_filter_autocompleter')
            ->setColumn($this->getColumn('status'))
            ->toHtml();
    }

filter_condition_callback

        $this->addColumn('apply_to', array(
            'header'    => Mage::helper('benefit')->__('Apply To'),
            'align'     => 'left',
            'index'     => 'apply_to',
            'renderer'  => 'benefit/adminhtml_attribute_grid_renderer_applyTo',
            'type'      => 'options',
            'options'   => Mage::helper('benefit')->getCustomerGroupOptionHash(),
            'filter_condition_callback' => [$this, '_findInSet'],
        ));
        
        return $this;
    }
    
    protected function _findInSet($collection, $column)
    {
        if ($value = $column->getFilter()->getValue()) {
            $collection->addFieldToFilter('apply_to', ['finset' => $value]);
        }
    }
    
    /**
     * Allow wildcard % in column search
     *
     * @param Mage_Core_Model_Resource_Db_Collection_Abstract $collection
     * @param Mage_Adminhtml_Block_Widget_Grid_Column $column
     */
    protected function _allowWildcardInFilter($collection, $column)
    {
        if ($value = $column->getFilter()->getValue()) {
            if ($field = $column->getFilterIndex() ?: $column->getIndex()) {
                /** @var Mage_Core_Model_Resource_Helper_Mysql4 $helper */
                $helper = Mage::getResourceHelper('core');
                $likeExpression = $helper->addLikeEscape($value, [
                    'position' => 'any',
                    'allow_string_mask' => true
                ]);
                $collection->addFieldToFilter($field, ['like' => $likeExpression]);
            }
        }
    }
kiatng
Last edit
4 months ago
kiatng
Posted by kiatng to OpenMage (2015-08-05 08:27)