ChoiceFilter.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. use Bundle\Sonata\BaseApplicationBundle\Admin\FieldDescription;
  12. use Doctrine\ORM\QueryBuilder;
  13. class ChoiceFilter extends Filter
  14. {
  15. public function filter(QueryBuilder $queryBuilder, $alias, $field, $value)
  16. {
  17. if($this->getField()->isMultipleChoice()) {
  18. if(in_array('all', $value)) {
  19. return;
  20. }
  21. if(count($value) == 0) {
  22. return;
  23. }
  24. $queryBuilder->andWhere($queryBuilder->expr()->in(sprintf('%s.%s',
  25. $alias,
  26. $field
  27. ), $value));
  28. } else {
  29. if ($value === null || $value == 'all') {
  30. return;
  31. }
  32. $queryBuilder->andWhere(sprintf('%s.%s = :%s',
  33. $alias,
  34. $field,
  35. $this->getName()
  36. ));
  37. $queryBuilder->setParameter($this->getName(), $value);
  38. }
  39. }
  40. protected function configure()
  41. {
  42. parent::configure();
  43. }
  44. public function getFormField()
  45. {
  46. return new \Symfony\Component\Form\ChoiceField(
  47. $this->getName(),
  48. $this->description->getOption('filter_field_options', array())
  49. );
  50. }
  51. }