Recent Posts


Adding a Date Range to a Magento EAV Collection


Frustrated by Magento? Then you’ll love Commerce Bug, the must have debugging extension for anyone using Magento. Whether you’re just starting out or you’re a seasoned pro, Commerce Bug will save you and your team hours everyday. Grab a copy and start working with Magento instead of against it.

Updated for Magento 2! No Frills Magento Layout is the only Magento front end book you'll ever need. Get your copy today!

Programming Quickies

Quick dispatches from the life of a working programmer.

Dates and time are always messy to work with in programming environments, and coming up with the right set of filters to accurately represent a date range in Magento is no exception. This is “extra” true given the trickiness of creating nested OR queries with Magento’s ORM.

Fortunately, someone on the Magento core team already went through the trouble. The new product block’s _beforeToHtml method adds a “new from” date filter to a product collection.

#File: app/code/core/Mage/Catalog/Block/Product/New.php
protected function _beforeToHtml()
    $todayStartOfDayDate  = Mage::app()->getLocale()->date()

    $todayEndOfDayDate  = Mage::app()->getLocale()->date()

    $collection = Mage::getResourceModel('catalog/product_collection');

    $collection = $this->_addProductAttributesAndPrices($collection)
        ->addAttributeToFilter('news_from_date', array('or'=> array(
            0 => array('date' => true, 'to' => $todayEndOfDayDate),
            1 => array('is' => new Zend_Db_Expr('null')))
        ), 'left')
        ->addAttributeToFilter('news_to_date', array('or'=> array(
            0 => array('date' => true, 'from' => $todayStartOfDayDate),
            1 => array('is' => new Zend_Db_Expr('null')))
        ), 'left')
                array('attribute' => 'news_from_date', 'is'=>new Zend_Db_Expr('not null')),
                array('attribute' => 'news_to_date', 'is'=>new Zend_Db_Expr('not null'))
        ->addAttributeToSort('news_from_date', 'desc')


    return parent::_beforeToHtml();

Copyright © Alan Storm 1975 – 2020 All Rights Reserved

Originally Posted: 15th January 2013