Symfony视图传参报错:变量date不存在,求解决方案
问题排查与解决
1. Twig模板「Variable "date" does not exist」错误
你的表单action里硬编码了date变量,但渲染模板时并没有从控制器传递该变量到Twig。而且GET表单无需提前把参数写进action路径,提交时会自动携带表单控件的参数,修正如下:
<form method="GET" action="{{ path('entree_filter') }}"> <!-- 其余表单代码保持不变 --> </form>
2. 控制器路由与参数接收问题
当前路由@Route("/{date}/{fournisseur}", name="entree_filter")要求URL必须包含date和fournisseur路径参数,但表单是GET提交,参数会放在URL query中(例如?date=2024-05-20&fournisseur=1)。需要修改路由为可选参数,或直接通过Request接收query参数:
use Symfony\Component\HttpFoundation\Request; use App\Repository\FournisseurRepository; /** * @Route("/filter", name="entree_filter") */ public function entreeFilter(ManagerRegistry $doctrine, Request $request, FournisseurRepository $fournisseurRepo): Response { // 从GET请求中获取参数,设置默认值避免空参数报错 $fournisseurId = $request->query->get('fournisseur'); $date = $request->query->get('date'); $entreeRepo = $doctrine->getRepository(Entree::class); $entrees = $entreeRepo->findEntreeByFrn($fournisseurId, $date); // 传递供应商列表到模板,保证下拉框正常渲染 $fournisseurs = $fournisseurRepo->findAll(); return $this->render('entree/index.html.twig', [ 'entrees' => $entrees, 'fournisseur' => $fournisseurs, 'selectedFournisseur' => $fournisseurId, 'selectedDate' => $date ]); }
注:原控制器未传递供应商列表到Twig,模板中的{% for fournisseurs in fournisseur %}会报错,需补充获取并传递。
3. Repository查询语法错误
你的QueryBuilder存在3个明显问题:
andWhere条件缺少等号,正确语法为字段名 = :参数名getResult是方法,需加括号调用getResult()- 方法参数顺序错误:控制器调用
findEntreeByFrn($fournisseurId,$date),但Repository方法定义为findEntreeByFrn($dates, $fournisseur),参数顺序完全颠倒
修正后的Repository代码:
public function findEntreeByFrn($fournisseurId, $date){ $qb = $this->createQueryBuilder('e'); // 添加非空判断,避免参数为空时生成无效查询 if ($fournisseurId) { $qb->andWhere('e.fournisseurId = :idFrn') ->setParameter('idFrn', $fournisseurId); } if ($date) { $qb->andWhere('e.entr_date = :dates') ->setParameter('dates', $date); } return $qb->getQuery()->getResult(); }
4. 表单回显选中值(可选优化)
如果需要提交后保留用户选择的日期和供应商,修改模板中的控件:
<input type="date" name="date" class="form-control" value="{{ selectedDate }}"> <select class="custom-select" name="fournisseur"> {% for item in fournisseur %} <option value="{{ item.id }}" {% if item.id == selectedFournisseur %}selected{% endif %}> {{ item.frnNom }} </option> {% endfor %} </select>
内容的提问来源于stack exchange,提问作者Meme Rak
相关产品推荐
相关产品推荐

