ChoiceFilter.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 (!is_array($value)) {
  18. return;
  19. }
  20. if ($this->getField()->getAttribute('multiple')) {
  21. if (in_array('all', $value)) {
  22. return;
  23. }
  24. if (count($value) == 0) {
  25. return;
  26. }
  27. $queryBuilder->andWhere($queryBuilder->expr()->in(sprintf('%s.%s',
  28. $alias,
  29. $field
  30. ), $value));
  31. } else {
  32. if ($value === null || $value == 'all') {
  33. return;
  34. }
  35. $queryBuilder->andWhere(sprintf('%s.%s = :%s',
  36. $alias,
  37. $field,
  38. $this->getName()
  39. ));
  40. $queryBuilder->setParameter($this->getName(), $value);
  41. }
  42. }
  43. public function defineFieldBuilder(FormFactory $formFactory, $value = null)
  44. {
  45. $options = $this->getFieldDescription()->getOption('filter_field_options', array('required' => false));
  46. $this->field = $formFactory->createNamedBuilder('choice', $this->getName(), $value, $options)->getForm();
  47. }
  48. }