Skip to content

Commit

Permalink
Add a how-to about prefixes for dynamic filtering (#6336)
Browse files Browse the repository at this point in the history
  • Loading branch information
kirya-dev authored Aug 28, 2020
1 parent 5ae2b30 commit 0c42eda
Showing 1 changed file with 35 additions and 14 deletions.
49 changes: 35 additions & 14 deletions docs/reference/form_types.rst
Original file line number Diff line number Diff line change
Expand Up @@ -267,20 +267,41 @@ The available options are:

From the ``$admin`` parameter it is possible to get the ``Datagrid`` and the ``Request``::

$formMapper
->add('category', ModelAutocompleteType::class, [
'property' => 'title',
'callback' => function ($admin, $property, $value) {
$datagrid = $admin->getDatagrid();
$queryBuilder = $datagrid->getQuery();
$queryBuilder
->andWhere($queryBuilder->getRootAlias() . '.foo=:barValue')
->setParameter('barValue', $admin->getRequest()->get('bar'))
;
$datagrid->setValue($property, null, $value);
},
])
;
$formMapper
->add('category', ModelAutocompleteType::class, [
'property' => 'title',
'callback' => static function (AdminInterface $admin, string $property, $value): void {
$datagrid = $admin->getDatagrid();
$queryBuilder = $datagrid->getQuery();
$queryBuilder
->andWhere($queryBuilder->getRootAlias() . '.foo=:barValue')
->setParameter('barValue', $admin->getRequest()->get('bar'))
;
$datagrid->setValue($property, null, $value);
},
])
;

If you want to dynamically change the ``property`` being filtered on to something else,
you can use a prefix system, as follows.
When the user types **id: 20** the property used for filtering is "id".
When they type **username: awesome_user_name**, it will be "username"::

$formMapper
->add('category', ModelAutocompleteType::class, [
'property' => 'title',
'callback' => static function (AdminInterface $admin, string $property, string $value): void {
$datagrid = $admin->getDatagrid();

$valueParts = explode(':', $value);
if (count($valueParts) === 2 && in_array($valueParts[0], ['id', 'email', 'username'])) {
[$property, $value] = $valueParts;
}

$datagrid->setValue($datagrid->getFilter($property)->getFormName(), null, $value);
},
])
;

``to_string_callback``
defaults to ``null``. Callable function that can be used to change the default toString behavior of entity::
Expand Down

0 comments on commit 0c42eda

Please sign in to comment.