austral / filter-bundle
Builder and mapper to filter austral
Package info
github.com/austral-project/filter-bundle
Type:symfony-bundle
pkg:composer/austral/filter-bundle
Requires
- php: ^8.0 || ^8.1 || ^8.2
- austral/form-bundle: ^3.1
- austral/tools-bundle: ^3.1
Requires (Dev)
None
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
Builder and mapper to filter austral
This bundle is part of Austral, a modular back office and CMS for Symfony.
filter-bundle describes the filters of a list, reads their values from the URL, builds their form with
form-bundle and applies them to a Doctrine query. The values live in the URL
(?filters[default][name]=foo): a filtered list can be shared, bookmarked and paginated, and the back
button of the browser works. Nothing is stored in the session.
Requirements
- PHP 8.4 or higher
- Symfony 7.4
- Doctrine ORM 3
Installation
composer require austral/filter-bundle
If you do not use Symfony Flex, register the bundle in config/bundles.php:
return [ // ... Austral\FilterBundle\AustralFilterBundle::class => ['all' => true], ];
The bundle has no configuration.
Usage
Describe the filters
use Austral\FilterBundle\Filter; use Austral\FilterBundle\Mapper\FilterMapper; $mapper = $filterMapperFactory->create('pages', ['translation_domain' => 'austral'], function (FilterMapper $mapper): void { $mapper->filter('default') ->add(new Filter\TextFilter('name')) ->add(new Filter\ChoiceFilter('type', ['choices' => ['choices.type.text' => 'text', 'choices.type.image' => 'image']])) ->add(new Filter\BooleanFilter('isEnabled', ['empty' => true])) ->add(new Filter\EntityFilter('category', ['class' => Category::class])) ->add(new Filter\RangeFilter('created', ['property_path' => 'createdAt'])) ->end() ->filter('homepage') ->add(new Filter\TextFilter('name')); });
A mapper holds groups of filters (filter('default'), filter('homepage')): one form and one set of URL
parameters per list. The factory (austral.filter.mapper_factory) dispatches FilterEvents::CONFIGURE_BEFORE,
calls the closure, then dispatches FilterEvents::CONFIGURE_AFTER.
Read the values and filter the query
$state = $filterHandler->handle($mapper, $request); // austral.filter.handler $queryBuilder = $repository->createQueryBuilder('root'); $filterApplier->apply($queryBuilder, $state->getCriteria('default')); // austral.filter.doctrine_applier
The handler submits the form of each group with its URL parameters. Only the valid fields give a value: a
malformed date, an unknown choice or an unknown id is ignored. FilterState gives the values
(getValues(), getValue(), hasValues()), the criteria (getCriteria()) and the forms (getForm()) of
each group.
FilterEvents::CRITERIA (CriteriaEvent) gives the criteria of a group before they are applied: a listener
can add, change or remove some (a domain, a status...).
Render
$views = $filterViewBuilder->build($state, $request); // austral.filter.view_builder
{{ include('@AustralFilter/filter/austral_filter.html.twig', {filter: views.default}) }}
The form is sent with GET, without CSRF token (it changes nothing). Its fields are rendered by the form
theme of the application (the admin theme, or @AustralForm/form/austral_layout.html.twig). The other
query parameters (sort, other groups) are kept as hidden fields; the reset parameters (page by default)
are dropped when a filter changes.
Filters
Common options:
| Option | Default | |
|---|---|---|
label |
fields.{name}.entitled |
Translation key, false for none |
property_path |
the name | Path from the filtered entity: category.name joins category |
field_options |
[] |
Options of the form-bundle field (placeholder, size, form_options...) |
visible |
true |
A hidden filter is neither rendered nor read |
format |
null |
Closure(value): string, the value displayed in the active filters |
The name of a filter is its field name and its URL parameter: letters, digits and _ only.
| Filter | Field | Criteria | Specific options |
|---|---|---|---|
TextFilter |
TextField | LIKE %…%, % and _ searched as such |
operator (contains, equal, starts_with, ends_with), case_sensitive (false) |
ChoiceFilter |
SelectField / ChoiceField | =, or IN when multiple; 0 and "0" are values |
choices (required, label => value), multiple, widget (select, choice), placeholder (filter.all) |
EntityFilter |
EntityField | = / IN on the association, the URL holds the ids |
class (required), multiple, choice_label, query_builder, placeholder |
BooleanFilter |
SelectField | = true, = false, IS NULL with empty |
empty (false), yes_label, no_label, empty_label, placeholder |
DateFilter |
DateField | the whole day: >= day 00:00 and < next day 00:00 |
display_format (Y-m-d) |
RangeFilter |
two fields {name}_from / {name}_to in a group |
>= from, <= to (dates: < to + 1 day) |
type (date, number), from_label, to_label, display_format |
SearchFilter |
TextField | one text in several properties, OR between them | properties (required), and the options of TextFilter; label filter.search.entitled |
EnumFilter |
SelectField / ChoiceField | a ChoiceFilter on the cases of a backed enum, compared by backing value |
enum (required), label_prefix (label {prefix}{value}, the case name without), cases |
NumberFilter |
NumberField | a number with an operator, 0 is a value |
operator (= by default, <>, >, >=, <, <=) |
ExistsFilter |
SelectField | set: IS NOT NULL, not set: IS NULL; on a collection IS NOT EMPTY / IS EMPTY |
yes_label, no_label, placeholder |
PeriodFilter |
SelectField | a period from today: >= first day 00:00 and < day after the last 00:00 |
periods (today, yesterday, last_7_days, last_30_days, this_week, last_week, this_month, last_month, this_year, last_year), label_prefix (filter.period.), now (Closure(): DateTimeInterface, for tests) |
A filter of your own extends Filter: buildForm() adds its fields, normalize() turns the submitted data
into its value (null when unused), criteria() gives its criteria, display() its active values.
Criteria and Doctrine
A filter gives conditions, not DQL: Criterion objects (path, Operator, value, case insensitive) and
CriteriaGroup objects (CriteriaGroup::or(...), CriteriaGroup::and(...), groups included). The
DoctrineFilterApplier applies them to a QueryBuilder, AND between them:
- the path is checked against the mapping of the root entity (unknown field or association: exception);
- each single-valued association of the path is left-joined once (
austral_filter_category...), an existing join on the same association is reused; - from a collection (one-to-many, many-to-many) on, the condition is an
EXISTSsubquery: an item that matches through several elements of the collection is found once and the count of the pagination stays right (translates.title,tags.name); on a collection itself,IS NULL/IS NOT NULLbecomeIS EMPTY/IS NOT EMPTYand=/INcompare its elements; - every value is a parameter with a unique name, typed from the mapping of the field;
INtakes an array,IS NULL/IS NOT NULLtake no value,LIKEescapes with!(DoctrineFilterApplier::escapeLike());- a case insensitive criterion compares
LOWER()of the field.
Mapper options
| Option | Default | |
|---|---|---|
parameter |
filters |
URL parameter: filters[group][field] |
translation_domain |
messages |
Domain of the labels and of the form |
reset_parameters |
['page'] |
Parameters removed when a filter changes |
View contract
views[group]: name, id ({mapper}-filter-{group}), label, translation_domain, form (FormView), action,
preserved[]: name, value (hidden fields),
active[]: filter, fields, label, label_parameters, value (string or list), translate_value, remove_url,
has_values, clear_url
Theme
The minimal theme @AustralFilter/filter/austral_filter.html.twig renders the active values and the form,
with escaped values. To change the markup, extend it and override the blocks you need (see
blocks.html.twig):
{% extends '@AustralFilter/filter/austral_filter.html.twig' %}
{% block austral_filter_active_item %}
<li>{{ active.label|trans }}: {{ active.value }} <a href="{{ active.remove_url }}">×</a></li>
{% endblock %}
Translation keys used by the filters and the theme: the labels, filters.title, filter.all,
filter.search, filter.clear, filter.remove (%label%, %value%), filter.boolean.yes,
filter.boolean.no, filter.boolean.empty, filter.search.entitled, filter.exists.yes,
filter.exists.no, filter.period.{period}.
Documentation
The full documentation is available at https://austral.dev.
Versions
| Bundle | Symfony | PHP | Branch |
|---|---|---|---|
| 4.x | 7.4 | ≥ 8.4 | 4.x |
| 3.1 | 5.4 / 6.4 | ≥ 8.0 | 3.1 (maintenance) |
See the CHANGELOG and, to upgrade from 3.1, UPGRADE-4.0.
Contributing
Contributions are welcome: see the contributing guide. To report a security issue, follow the security policy.
License
MIT, see LICENSE.
Credits
Created by Matthieu Beurel. Sponsored by Yipikai Studio.