13

I want to filter collection according :

  • start date < today
  • end date > today

I try this but my getSlides() function return empty results

<?php

namespace Vendor\Module\Block;

use Magento\Backend\Block\Template\Context;
use Vendor\Module\Api\Data\SlideInterface;
use Vendor\Module\Model\ResourceModel\Slide\CollectionFactory as SlideCollectionFactory;

class Carrousel extends \Magento\Framework\View\Element\Template
{
    /** @var \Vendor\Module\Model\ResourceModel\Slide\CollectionFactory */
    protected $slideCollection;

    /**
     * @param \Magento\Backend\Block\Template\Context $context
     * @param \Vendor\Module\Model\ResourceModel\Slide\CollectionFactory $slideCollection
     * @param array $data
     */
    public function __construct(
        Context $context,
        SlideCollectionFactory $slideCollection,
        array $data = []
    )
    {
        parent::__construct($context, $data);
        $this->slideCollection = $slideCollection;
    }

    public function getSlides()
    {
        $now = new \DateTime();

        $slides = $this->slideCollection->create()
        ->addFilter('startDate', ['lteq' => $now->format('Y-m-d H:i:s')])
        ->addFilter('endDate', ['gteq' => $now->format('Y-m-d H:i:s')]);

        return (count($slides) > 0) ? $slides : false;
    }
}

Please help me...

2
  • Can you provide more information on the collection you are filtering? Is this a 3rd party module or custom? It's common practice in m1/m2 for database columns to be named using underscores i.e. start_date
    – Ash Smith
    Feb 16, 2017 at 10:00
  • I've edit my answer Feb 16, 2017 at 10:09

1 Answer 1

33

Has force to seek and test several solutions I finally found !

Like I use CollectionFactory object I have to use addFieldToFilter() and not addFilter().

$slides = $this->slideCollection->create()
        ->addFieldToFilter('startDate', ['lteq' => $now->format('Y-m-d H:i:s')])
        ->addFieldToFilter('endDate', ['gteq' => $now->format('Y-m-d H:i:s')]);

It works perfectly!

2
  • 1
    This is super awesome, thankyou! Jan 7, 2021 at 17:26
  • It might be helpful to also add an OR null condtion to also fetch those records which do not have explicitly set a from or or date. ->addFieldToFilter('from_date', [['lteq' => $today], ['null' => true]]) the same goes for 'to_date'
    – Akif
    Oct 12, 2022 at 8:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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