BooleanFilter.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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 Bundle\Sonata\BaseApplicationBundle\Filter;
  11. class BooleanFilter extends Filter
  12. {
  13. public function filter($query_builder, $alias, $field, $value)
  14. {
  15. if($this->getField()->isMultipleChoice()) {
  16. $values = array();
  17. foreach($value as $v) {
  18. if($v == 'all') {
  19. return;
  20. }
  21. $values[] = $v == 'true' ? 1 : 0;
  22. }
  23. if(count($values) == 0) {
  24. return;
  25. }
  26. $query_builder->andWhere($query_builder->expr()->in(sprintf('%s.%s',
  27. $alias,
  28. $field
  29. ), $values));
  30. } else {
  31. if ($value === null || $value == 'all') {
  32. return;
  33. }
  34. $value = $value == 'true' ? 1 : 0;
  35. $query_builder->andWhere(sprintf('%s.%s = :%s',
  36. $alias,
  37. $field,
  38. $this->getName()
  39. ));
  40. $query_builder->setParameter($this->getName(), $value);
  41. }
  42. }
  43. protected function configure()
  44. {
  45. parent::configure();
  46. }
  47. public function getFormField()
  48. {
  49. $options = array(
  50. 'choices' => array(
  51. 'all' => 'all',
  52. 'true' => 'true',
  53. 'false' => 'false'
  54. )
  55. );
  56. $options = array_merge($options, $this->description['filter_field_options']);
  57. return new \Symfony\Component\Form\ChoiceField(
  58. $this->getName(),
  59. $options
  60. );
  61. }
  62. }