BooleanFilter.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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\BaseApplicationBundle\Filter;
  11. use Sonata\BaseApplicationBundle\Admin\FieldDescription;
  12. use Doctrine\ORM\QueryBuilder;
  13. class BooleanFilter extends Filter
  14. {
  15. public function filter(QueryBuilder $queryBuilder, $alias, $field, $value)
  16. {
  17. if ($this->getField()->isMultipleChoice()) {
  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. $value = $value == 'true' ? 1 : 0;
  37. $queryBuilder->andWhere(sprintf('%s.%s = :%s',
  38. $alias,
  39. $field,
  40. $this->getName()
  41. ));
  42. $queryBuilder->setParameter($this->getName(), $value);
  43. }
  44. }
  45. protected function configure()
  46. {
  47. parent::configure();
  48. }
  49. public function getFormField()
  50. {
  51. $options = array(
  52. 'choices' => array(
  53. 'all' => 'all',
  54. 'true' => 'true',
  55. 'false' => 'false'
  56. ),
  57. 'required' => false
  58. );
  59. $options = array_merge($options, $this->description->getOption('filter_field_options', array()));
  60. return new \Symfony\Component\Form\ChoiceField(
  61. $this->getName(),
  62. $options
  63. );
  64. }
  65. }