[英]Form with variable number of criterias on Symfony4 / Doctrine2
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. 让我们以https://symfony.com/doc/current/forms.html#building-the-form示例表单为例,但仅用于任务列表中的搜索而不是保存。
Goal is to allow searches on task, dueDate or both criterias (in my real case, I have 9 criterias) 目标是允许搜索任务,DueDate或两个条件(在我的实际情况下,我有9个条件)
Here are src/Repository/ResultRepository.php : 这是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)! 它需要两个条件才能返回结果!
I ran a lot of searches and find: 我进行了很多搜索,发现:
So I code a $where_string variable to construct my variable where. 因此,我编写了$ where_string变量以在哪里构造变量。 and a $parameters to construct my variable parameters array, and my findMultiKeys becomes:
和$ parameters构造我的可变参数数组,我的findMultiKeys变成:
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
在搜索中,我发现当然可以使用ElasticSearch ,或者满足我的简单需求,或者我找到了PetkoparaMultiSearchBundle
Bests solutions welcomes 最佳解决方案欢迎
I have a proposition :-) 我有一个建议:-)
create a form type with this "data_class" 使用此“ data_class”创建表单类型
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()); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.