datagrid icon indicating copy to clipboard operation
datagrid copied to clipboard

Using setFilterDateRange() for filtering by year of birth

Open milsorm opened this issue 3 years ago • 3 comments

I am trying to solve limiting datagrid with people by range of their year of birth.

If I use $col->setFilterDateRange()->setFormat( 'Y', 'yyyy' ); for limiting filter to year on ColumnDateTime, I have to enter year+1 to "to" field, because internally in applyFilterDateRange() is used as DAY not YEAR with 23:59:59 time.

Is it possibility to add setCondition or formatting for YEAR( column ) to check of this filter? I didn't find a way.

Anyway applyFilterRange() cannot help because there is fix use of column <= int and I cannot pass YEAR( column) to column.

I am using Nextras ORM as data source.

milsorm avatar Feb 10 '21 08:02 milsorm

Solution:

  • create FilterYearRange as descendant of FilterDateRange which inside constructor calls setCondition to specific use of QueryBuilder to create conditoin with YEAR( column )
  • descendant of DataGrid has addFilterYearRange due to necessity to call addFilterCheck and manually inserting new FilterYearRange to filters
  • formatting is done in template

The question is if:

  • create year range as new filter inside DataGrid distribution? too specific
  • adding ability to addCustomFilter which pass any new filter object into filters and call addFilterCheck? very helpful but quite low level
  • adding ability to pass setFilterCondition to DateRange (or other filters) which will go directly to inner filter instance? helpful and more straightforward

Solution with new descendants is also possible (and I am using it) but duplicates some code which is bad for maintanance with new versions.

I am using DataGrid together with Nextras ORM havily in new project for non-government organization so this is why I am creating new issues :-( Sorry for that.

milsorm avatar Mar 21 '21 11:03 milsorm

You could simplify your solution by calling setCondition (docs) on your dateFilter and provide custom template with setTemplate (docs) like in this snippet:

$grid->addFilterDateRange('born', 'Year of birth')
    // when working with Nextras/ORM (Nextras/Dbal), DbalCollection is first argument.
    ->setCondition(function(DbalCollection $source, $value) {
        $qb = $source->getQueryBuilder();
        $qb->andWhere('YEAR(column) = %s', /** here handle $value as you need */);
    })
    // use setTemplate, or use tempate block as can be seen in documentaion linked above
    ->setTemplate(/** path_to_your_year_date_range_filter_template.latte **/)

mskocik avatar Mar 24 '21 09:03 mskocik

Good point, thanks. This is like my third bullet in question and it works. Thanks.

milsorm avatar Mar 24 '21 09:03 milsorm