3

if news_to_date is empty i get syntax error, how can i check if news_to_date is empty or not? Code below, thanks

\Magento\Framework\Stdlib\DateTime\DateTime $stdlibDateTime, 

$currentTime = $this->_date->date();
$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->addAttributeToSelect(array('entity_id','sku'));     
$collection->addFieldToFilter('news_from_date', ['lteq' => $currentTime])
        ->addFieldToFilter('news_to_date', ['gteq' => $currentTime])
        ->setOrder('sort_order', 'ASC');

enter image description here

2

You can try this code instead:

$todayStartOfDayDate = $this->_date->date()->setTime(0, 0, 0)->format('Y-m-d H:i:s');
$todayEndOfDayDate = $this->_date->date()->setTime(23, 59, 59)->format('Y-m-d H:i:s');
$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->addAttributeToSelect(array('entity_id','sku'));

$collection->addAttributeToFilter(
        'news_from_date',
        [
            'or' => [
                0 => ['date' => true, 'to' => $todayEndOfDayDate],
                1 => ['is' => new \Zend_Db_Expr('null')],
            ]
        ],
        'left'
    )->addAttributeToFilter(
        'news_to_date',
        [
            'or' => [
                0 => ['date' => true, 'from' => $todayStartOfDayDate],
                1 => ['is' => new \Zend_Db_Expr('null')],
            ]
        ],
        'left'
    )->addAttributeToFilter(
        [
            ['attribute' => 'news_from_date', 'is' => new \Zend_Db_Expr('not null')],
            ['attribute' => 'news_to_date', 'is' => new \Zend_Db_Expr('not null')],
        ]
    );

$collection->setOrder('sort_order', 'ASC');

Hope this will work for you

4
  • \ Zend_news_from_dateDb_Expr replaced with \ Zend_Db_Expr and it works great, thanks – Rub Hayrapetyan May 17 at 14:22
  • with \Zend_news_from_dateDb_Expr i getting error :) – Rub Hayrapetyan May 17 at 14:23
  • Great. +1 for answer acceptance :) – Shoaib Munir May 17 at 14:31
  • You can edit my answer as well, as you found a bug in it – Shoaib Munir May 17 at 14:32
2

I think you could try something like this

$collection->addFieldToFilter('news_to_date',  ['neq' => NULL, 'gteq' => $currentTime]);

code is not tested, but should work :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.