phpsymfonysonata-adminsonata

Default date filter is not working in Sonata Admin Bundle


I have a list of users and I'm trying to set up a default filter on the createdAt attribute to get by default the users created in the last month rather than all the users at once.

Here's my current attempt:

Entity\User.php

#[ORM\Column(name: 'creation_date', type: 'datetime', nullable: true)]
private ?DateTime $createdAt = null;

UserAdmin.php

protected function configureDatagridFilters(DatagridMapper $datagridMapper): void
{
    $datagridMapper->add('createdAt', DateTimeRangeFilter::class, [
                'field_type' => DateTimeRangePickerType::class,
            ])
    ...
}

protected function configureDefaultFilterValues(array &$filterValues): void
{
    $filterValues['createdAt'] = [
        'value' => [
            'start' =>  (new \DateTime())->modify('-1 month')->format('M d, Y, h:i:s a'),
            'end' => (new \DateTime())->format('M d, Y, h:i:s a'),
        ],
    ];
}

Solution

  • It was a formatting issue. Between the seconds and the 'am/pm' there was a special character (Narrow No-Break Space) which was f-ing up the whole filter. My code ended up like this :

    protected function configureDefaultFilterValues(array &$filterValues): void
    {
        $start = (new \DateTime())->modify('-1 month')->format('F j, Y, g:i:sa');
        $end = (new \DateTime())->format('F j, Y, g:i:sa');
        $filterValues['createdAt'] = [
            'value' => [
                'start' =>  (new \DateTime())->modify('-7 day')->format('M d, Y, h:i:s a'),
                'end' => (new \DateTime())->format('M d, Y, h:i:s a'),
                'start' =>  preg_replace('/(am|pm)$/', "\u{202F}\$0", $start),
                'end' =>  preg_replace('/(am|pm)$/', "\u{202F}\$0", $end),
            ],
        ];
    }