You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

78 lines
2.7KB

  1. <?php
  2. namespace Lc\SovBundle\Field\Filter;
  3. use Doctrine\ORM\QueryBuilder;
  4. use EasyCorp\Bundle\EasyAdminBundle\Dto\FieldDto;
  5. use Lc\SovBundle\Translation\TranslatorAdmin;
  6. use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
  7. use Symfony\Component\Form\FormBuilderInterface;
  8. use function Symfony\Component\String\u;
  9. /**
  10. * @author La clic ! <contact@laclic.fr>
  11. */
  12. class ChoiceFilter
  13. {
  14. use FilterTrait;
  15. protected $translatorAdmin;
  16. public function __construct(?TranslatorAdmin $translatorAdmin = null)
  17. {
  18. $this->translatorAdmin = $translatorAdmin;
  19. }
  20. public function buildProperty(FormBuilderInterface $builder, FieldDto $fieldDto, $options = array())
  21. {
  22. $entity = new $options['entity_class'];
  23. $choicesFct = 'get'.u($fieldDto->getProperty())->title()->toString().'Choices';
  24. if (method_exists($entity, $choicesFct)) {
  25. $builder->add(
  26. $fieldDto->getProperty(),
  27. ChoiceType::class,
  28. array(
  29. 'required' => false,
  30. 'choices' => $this->translatorAdmin->transChoices(
  31. $entity->$choicesFct(),
  32. $options['entity_name'],
  33. $fieldDto->getProperty()
  34. ),
  35. 'attr' => array(
  36. 'class' => 'select2 input-sm',
  37. 'form' => 'filters-form',
  38. ),
  39. )
  40. );
  41. }
  42. }
  43. public function applyFilter(QueryBuilder $queryBuilder, string $fieldProperty, string $filteredValue = null)
  44. {
  45. if ($filteredValue !== null) {
  46. if ($this->isRelationField($fieldProperty)) {
  47. $aliasRelation = $this->getFieldPropertyRelationAlias($fieldProperty);
  48. if (array_search($aliasRelation, $queryBuilder->getAllAliases()) === false) {
  49. $queryBuilder->innerJoin('entity.'.$aliasRelation, $aliasRelation);
  50. }
  51. $queryBuilder->andWhere(
  52. $fieldProperty.' LIKE :'.$this->getFieldPropertySnake($fieldProperty).''
  53. );
  54. $queryBuilder->setParameter(
  55. $this->getFieldPropertySnake($fieldProperty),
  56. '%'.$filteredValue.'%'
  57. );
  58. } else {
  59. $queryBuilder->andWhere(
  60. 'entity.'.$fieldProperty.' LIKE :'.$fieldProperty.''
  61. );
  62. $queryBuilder->setParameter($fieldProperty, '%'.$filteredValue.'%');
  63. }
  64. }
  65. }
  66. }