为了账号安全,请及时绑定邮箱和手机立即绑定

Symfony:从变量中获取 FormType 名称

Symfony:从变量中获取 FormType 名称

PHP
慕的地8271018 2021-10-22 15:12:22
在我的项目中,当我更改选择时,ajax 调用会获取一个新的选择元素并将其替换为我当前的元素。所以基本上,我的 Ajax 调用是/ticket/owner-select为了获取所有者选项。一切正常。这是我的网址控制器://TicketController.php.../** * @Route("/ticket/owner-select", name="app_ticket_owner_select", methods={"GET"}, condition="request.isXmlHttpRequest()") */public function getTicketOwnerSelect(Request $request, DepartmentRepository $departmentRepository){    $department = $departmentRepository->findOneBy(['id' => $request->query->get('value')]); //gets id from get-parameter    if(!$department) {        return new Response(null, 204); //return empty response if no department selected or found    }    $ticket = new Ticket();    $ticket->setDepartment($department);    $form = $this->createForm(TicketType::class, $ticket);    if(!$form->has('owner')) {        return new Response(null, 204); //return empty response    }    return $this->render('ticket/select.html.twig', ['form' => $form->createView()]); //render the select element with correct options}...现在我想为其他FormType重用完全相同的 url ,因为我有多个表单,其中所有者根据另一个选择字段而改变。例子:$form = $this->createForm(TicketType::class, $ticket);$form = $this->createForm(AnotherTicketType::class, $ticket);$form = $this->createForm(AnotherAnotherTicketType::class, $ticket);所以 FormType 应该是动态的。可能最好的方法是另一个 get 参数,但我不太确定如何做到这一点,尤其是检查该类型是否存在(错误处理)。原因:对于每个工单表单上的每个选择字段,控制器看起来都一样。由于我不想要重复的代码(大部分),我想创建一个动态解决方案。Mabye有人可以帮助我。提前致谢。
查看完整描述

2 回答

?
波斯汪

TA贡献1811条经验 获得超4个赞

您已经通过 ajax 请求(id参数)中的查询字符串将参数传递给控制器,所以我假设您知道如何添加新参数,比如说type.


由于::class只返回一个具有完全限定类名的字符串,您可以使用这个新参数来构建您的FormType类并正常实例化它。如果请求的类型不存在,createForm将抛出InvalidArgumentException.


$ticketType = $request->query->get('type', ''); // Set 'main' type if not specified

$ticketFormType = 'App\Form\' . $ticketType . 'TicketType';


$ticket = new Ticket();


try {

    $form = $this->createForm(TicketType::class, $ticket);

} catch (Symfony\Component\Form\Exception\InvalidArgumentException $e) {

     // FormType doesn't exist

     return new Response(null, 400);

}


return $this->render('ticket/select.html.twig', ['form' => $form->createView()]);


查看完整回答
反对 回复 2021-10-22
?
慕婉清6462132

TA贡献1804条经验 获得超2个赞

带有类型的隐藏字段怎么样?


查看完整回答
反对 回复 2021-10-22
  • 2 回答
  • 0 关注
  • 130 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信