BooleanFilter.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. /*
  3. * This file is part of the Sonata package.
  4. *
  5. * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Sonata\AdminBundle\Filter\ORM;
  11. use Doctrine\ORM\QueryBuilder;
  12. use Symfony\Component\Form\FormFactory;
  13. class BooleanFilter extends Filter
  14. {
  15. public function filter($queryBuilder, $alias, $field, $value)
  16. {
  17. if ($this->getField()->getAttribute('multiple')) {
  18. $values = array();
  19. foreach ($value as $v) {
  20. if ($v == 'all') {
  21. return;
  22. }
  23. $values[] = $v == 'true' ? 1 : 0;
  24. }
  25. if (count($values) == 0) {
  26. return;
  27. }
  28. $queryBuilder->andWhere($queryBuilder->expr()->in(sprintf('%s.%s',
  29. $alias,
  30. $field
  31. ), $values));
  32. } else {
  33. if ($value === null || $value == 'all') {
  34. return;
  35. }
  36. $queryBuilder->andWhere(sprintf('%s.%s = :%s',
  37. $alias,
  38. $field,
  39. $this->getName()
  40. ));
  41. $queryBuilder->setParameter($this->getName(), $value == 'true' ? 1 : 0);
  42. }
  43. }
  44. public function defineFieldBuilder(FormFactory $formFactory)
  45. {
  46. $options = array(
  47. 'choices' => array(
  48. 'all' => 'all',
  49. 'true' => 'true',
  50. 'false' => 'false'
  51. ),
  52. 'required' => true
  53. );
  54. $options = array_merge($options, $this->getFieldDescription()->getOption('filter_field_options', array()));
  55. $this->field = $formFactory->createNamedBuilder('choice', $this->getName(), null, $options)->getForm();
  56. }
  57. }