Easyadmin add an option for every filter to be inclusive or exclusive (use OR or AND)

Viewed 272

I'm trying to modify easyadmin filters to include an option to change de behaviour of the query from "andWhere" to "orWhere" and give the possibility to make the filters non-exclusive.

I'm trying with the class ComparysonFilterType adding a checkbox:

 public function buildForm(FormBuilderInterface $builder, array $options): void
        {
            $builder->add('comparison', $options['comparison_type'], $options['comparison_type_options']);
            $builder->add('value', FormTypeHelper::getTypeClass($options['value_type']), $options['value_type_options'] + [
                'label' => false,
            ]);
#I've added this field
$builder->add('useOr', CheckboxType::class, [
              'label' => 'no excluyente',
              'required' => false
            ]);
    
        }

And then I'm changing the filter function with a simple conditional:

public function filter(QueryBuilder $queryBuilder, FormInterface $form, array $metadata)
{
    $alias = current($queryBuilder->getRootAliases());
    $property = $metadata['property'];
    $paramName = static::createAlias($property);
    $data = $form->getData();

    #I've added this lines
    if(true === $data["useOr"]){
      $queryBuilder->orWhere(sprintf('%s.%s %s :%s', $alias, $property, $data['comparison'], $paramName))
          ->setParameter($paramName, $data['value']);
    }else{
      $queryBuilder->andWhere(sprintf('%s.%s %s :%s', $alias, $property, $data['comparison'], $paramName))
          ->setParameter($paramName, $data['value']);
    }


}

This works but maybe there is another approach with custom filters more clean to achieve this goal. I'm trying not to modify the original classes.

I would like to give this option in any filterType and not only in "ComparisonFilterType"

Any suggests

0 Answers
Related