Skip to content

Instantly share code, notes, and snippets.

@webdevilopers
Last active August 5, 2018 03:28
Show Gist options
  • Save webdevilopers/c04abcff801c7837d25f to your computer and use it in GitHub Desktop.
Save webdevilopers/c04abcff801c7837d25f to your computer and use it in GitHub Desktop.
(NOT) NULL doctrine_orm_callback filter with Sonata Admin
<?php
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\CoreBundle\Form\Type\BooleanType;
class PersonAdmin extends Admin
{
protected function configureDatagridFilters(DatagridMapper $filterMapper)
{
$filterMapper
->add('user', 'doctrine_orm_callback', array(
'label' => 'Login',
'translation_domain' => 'SonataCoreBundle',
'callback' => function($queryBuilder, $alias, $field, $value) {
if (!isset($value['value'])) {
return;
}
if ($value['value'] == BooleanType::TYPE_YES) {
$queryBuilder->andWhere(sprintf('$s.$s IS NOT NULL', $alias, $field));
}
if ($value['value'] == BooleanType::TYPE_NO) {
$queryBuilder->andWhere(sprintf('$s.$s IS NULL', $alias, $field));
}
return true;
}
), 'choice', array(
'translation_domain' => 'SonataCoreBundle',
'choices' => array(
BooleanType::TYPE_YES => 'label_type_yes',
BooleanType::TYPE_NO => 'label_type_no'
)
)
)
;
}
}
@webdevilopers
Copy link
Author

Related issue $field in doctrine_orm_callback is empty:

Based on:

@webdevilopers
Copy link
Author

FR Filter for a "IS_NULL" Field:

@cassianotartari
Copy link

Just a fill considerations:

  1. sprintf should not use %s instead of $s that you used?
  2. Under Symfony 2.8+ value and keys in choices are inverted like below:
'choices' => array(
    'label_type_yes' => BooleanType::TYPE_YES,
    'label_type_no'  => BooleanType::TYPE_NO
)

@IvanAlekseevichPopov
Copy link

Why $s in $queryBuilder->andWhere(sprintf('$s.$s IS NOT NULL', $alias, $field)); instead %s?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment