ChoiceFilter.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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 Symfony\Component\Form\FormFactory;
  12. use Doctrine\ORM\QueryBuilder;
  13. class ChoiceFilter extends Filter
  14. {
  15. public function filter($queryBuilder, $alias, $field, $value)
  16. {
  17. if ($this->getField()->getAttribute('multiple')) {
  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. public function defineFieldBuilder(FormFactory $formFactory, $value = null)
  41. {
  42. $options = $this->getFieldDescription()->getOption('filter_field_options', array('required' => false));
  43. $this->field = $formFactory->createNamedBuilder('choice', $this->getName(), $value, $options);
  44. }
  45. }