0

Let's take https://symfony.com/doc/current/forms.html#building-the-form example form but only for Search in tasks list instead of save.

Goal is to allow searches on task, dueDate or both criterias (in my real case, I have 9 criterias)

Here are src/Repository/ResultRepository.php :

class ResultRepository extends ServiceEntityRepository
{
    public function __construct(RegistryInterface $registry)
    {
        parent::__construct($registry, Result::class);
    }

    public function findMultiKeys($task, $dueDate): array
    {
        $qb = $this->createQueryBuilder('d')
            ->andWhere('d.task = :task')
            ->setParameter('task', $task)
            ->andWhere('d.dueDate = :dueDate')
            ->setParameter('dueDate', $dueDate)
            ->getQuery();

        return $qb->execute();
    }   
}

It require both criterias to return result(s)!

bcag2
  • 1,988
  • 1
  • 17
  • 31

2 Answers2

0

I ran a lot of searches and find:

So I code a $where_string variable to construct my variable where. and a $parameters to construct my variable parameters array, and my findMultiKeys becomes:

public function findMultiKeys($get_form): array
{
    $where_string = '';
    $parameters = [];
    $task = $get_form->getTask();
    if ($task !== null) {
        $where_string .= "d.task = :task";
        $parameters += array('task' => $task);
    }
    $dueDate = $get_form->getDueDate();
    if ($dueDate !== null) {
        if ($where_string !== '')
            $where_string .= " AND ";
        $where_string .= "d.dueDate = :dueDate";
        $parameters += array('dueDate' => $dueDate);
    }

    $qb = $this->createQueryBuilder('d')
        ->where($where_string)
        ->setParameters($parameters)
        ->getQuery();

    return $qb->execute();
}   

It works, perhaps not the best way? In my searches, I found, of course, to use ElasticSearch, perhaps to much to my simple need, or I found PetkoparaMultiSearchBundle

Bests solutions welcomes

bcag2
  • 1,988
  • 1
  • 17
  • 31
0

I have a proposition :-)

  1. You can build an task4Seach entity with your 9 criteria (without persistance)
  2. create a form type with this "data_class"

  3. use it to get your datas in your repository

$qb = $this->createQueryBuilder('d');

...
if ($task4Seach ->getDueDate()) {
          $qb->andWhere($qb->expr()->eq('d.dueDate', ':dueDate'));
          $qb->setParameter('dueDate', $task4Seach->getDueDate());
 }
Bruno
  • 21
  • 2
  • 1. what is the difference with the __Task__ entity from example https://symfony.com/doc/current/forms.html#creating-a-simple-form 2. https://symfony.com/doc/current/forms.html#building-the-form , ok 3. how to solve only task, only dueDate, or both? – bcag2 Oct 22 '18 at 14:38