Home » Blog » Dev notes » DEFAULT FILTER FOR MAGENTO GRID BY USING OBSERVER

DEFAULT FILTER FOR MAGENTO GRID BY USING OBSERVER

thumbnail

Sometimes you need to add a default filter for your Magento admin grid. Perhaps you ask yourself do I need to override any class to do this? The answer is simple – No, You don’t!

In this post I will show you how to add default grid filter for default Magento grid (Sales Order Grid) by using observer.

To make the example clear, imagine that you would like to add default filter to Sales Order Grid which filter you orders collection by one condition: orders were placed yesterday.

Before we start to write the example module, lets see a part of the code below (Mage_Adminhtml_Block_Widget_Grid::_prepareCollection).

$filter   = $this->getParam($this->getVarNameFilter(), null);
 
if (is_null($filter)) {
    $filter = $this->_defaultFilter;
}
 
if (is_string($filter)) {
    $data = $this->helper('adminhtml')->prepareFilterString($filter);
    $this->_setFilterValues($data);
}
else if ($filter && is_array($filter)) {
    $this->_setFilterValues($filter);
}
else if(0 !== sizeof($this->_defaultFilter)) {
    $this->_setFilterValues($this->_defaultFilter);
}

In this part of function _prepareCollection() we see, that magento is looking for predefined filters value. We create encoded string which will be processed by function prepareFilterString(…) from adminhtl helper. Function from helper decodes string and returns params to set the filter collection.

To create module which sets predefined filters follow these steps:

  1. Tell Magento about our module and create module structure.Create file: app/etc/modules/Light4website_PreparedGridFilter.xml
             <config>
        <modules>
            <light4website_preparedgridfilter>
                <active>true</active>
                <codepool>local</codepool>
            </light4website_preparedgridfilter>
        </modules>
    </config>
            

    Create file: app/code/local/Light4website/PreparedGridFilter/etc/config.xml

    <config>
        <modules>
            <light4website_preparedgridfilter>
                <version>0.1.0</version>
            </light4website_preparedgridfilter>
        </modules>
        <global>
            <models>
                <light4website_preparedgridfilter>
                    <class>Light4website_PreparedGridFilter_Model</class>
                </light4website_preparedgridfilter>
            </models>
            <blocks>
                <light4website_preparedgridfilter>
                    <class>Light4website_PreparedGridFilter_Block</class>
                </light4website_preparedgridfilter>
            </blocks>
            <helpers>
                <light4website_preparedgridfilter>
                    <class>Light4website_PreparedGridFilter_Helper</class>
                </light4website_preparedgridfilter>
            </helpers>
        </global>
    </config>
    

    Magento module structure

  2. Create observer which will observe the event before displaying Sales Order Grid which sets encoded default filters in Magento Request (event controller_action_predispatch_adminhtml_sales_order_index is the best event to add param to request)Register event observer in config.xml
    <config>
        ...
        <adminhtml>
            <events>
                <controller_action_predispatch_adminhtml_sales_order_index>
                    <observers>
                        <set_default_filter>
                            <type>singleton</type>
                            <class>Light4website_PreparedGridFilter_Model_Adminhtml_Sales_Order_Observer</class>
                            <method>setDefaultGridFilter</method>
                        </set_default_filter>
                    </observers>
                </controller_action_predispatch_adminhtml_sales_order_index>
            </events>
        </adminhtml>
    </config>
    

    CREATE OBSERVER CLASS

    Light4website_PreparedGridFilter_Model_Adminhtml_Sales_Order_Observer in file: app/code/local/Light4website/PreparedGridFilter/Model/Adminhtml/Sales/Order/Observer.php with method which will be set default encoded filter

    class Light4website_PreparedGridFilter_Model_Adminhtml_Sales_Order_Observer
    {
    /**
    * Set default grid filter
    *
    * @param Varien_Event_Observer $observer
    * @return $this
    */
    public function setDefaultGridFilter(Varien_Event_Observer $observer)
    {
      $request = Mage::app()->getFrontController()->getRequest();
     
      if (! $request->getParam('filter')) {
      $filter = $this->_getDefaultEncodedFilterString();
     
      Mage::app()->getFrontController()
       ->getRequest()
       ->setParam('filter', $filter);
    }
     
      return $this;
    }
    }
    
  3. Create method _getDefaultEncodedFilterString() and _getLocalCode in class Light4website_PreparedGridFilter_Model_Adminhtml_Sales_Order_Observer
    /**
     * @return string
     */
    protected function _getDefaultEncodedFilterString()
    {
        $helper = Mage::helper('light4website_preparedgridfilter');
        $yesterdaysDate = $helper->getYesterdaysDate();
     
        $data = array (
            'created_at'  =>
                array(
                    'from'   => $yesterdaysDate,
                    'to'       => $yesterdaysDate,
                    'locale' => $this->_getLocalCode()
                )
        );
     
        return $helper->createFilterString($data);
    }
     
    /**
     * @return string|null
     */
    protected function _getLocalCode()
    {
        return Mage::getStoreConfig('general/locale/code', Mage::app()->getStore()->getId());
    }
    
  4. Create Helper class Light4website_PreparedGridFilter_Helper_Data with helpful methods
    class Light4website_PreparedGridFilter_Helper_Data extends Mage_Core_Helper_Abstract
    {
    /**
    * Retrieve yesterday's date
    *
    * @return string
    */
    public function getYesterdaysDate()
    {
    $date = new DateTime();
    $date->add(DateInterval::createFromDateString('yesterday'));
     
    return $date->format('m/d/Y');
    }
     
    /**
    * Create encoded string for grid filter
    *
    * @param array $data
    * @return string
    */
    public function createFilterString(array $data)
    {
    array_walk_recursive($data, array($this, '_encodeFilter'));
    $query = http_build_query($data);
     
    return base64_encode($query);
    }
     
    /**
    * @param string $value
    */
    protected function _encodeFilter(&$value)
    {
    $value = trim(rawurlencode($value));
    }
    }
    
  5. Go to admin panel -> Sales -> Orders and check if it works

You can download this module from our repository.

Sharing is caring!

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)
Loading...

Leave a Reply

Your email address will not be published. Required fields are marked *

*

This site uses AMP for mobile version, check it out on the mobile device.