在我的Symfony 3项目中,我制作了以下控制器:
/**
* @Route("/person_in_need/{id}",name="person_in_need_view")
*/
public function viewPersonInNeed(Request $request,$id)
{
}
我想从另一个控制器重定向,例如:
/**
* @Route("/person_in_need/add",name="add_person_in_need")
*/
public function addPersonInNeed(Request $request)
{
$form=$this->createForm(PersonInNeedType::class,new PersonInNeed());
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
/**
* @var PersonInNeedBusinessLogicModel $dataInsert
*/
$dataInsert=$this->get('app.person_in_need_business_model');
$name=$form->get(PersonInNeedConstats::PERSON_IN_NEED_NAME)->getData();
$surname=$form->get(PersonInNeedConstats::PERSON_IN_NEED_SURNAME)->getData();
$reason=$form->get(PersonInNeedConstats::PERSON_IN_NEED_REASON)->getData();
$dataInsert->registerPersonInNeed($name,$surname,$reason);
//Pass id there
// return $this->redirectToRoute('person_in_need_view');
}
return $this->render('social_worker/add_person_in_need.html.twig',array(
'form'=>$form->createView()
));
}
我将如何使用路由名称重定向并传递id
参数?
答案 0 :(得分:3)
请参阅Link:
使用301返回代码重定向到客户端:
$this->redirect(
$this->generateUrl(
'person_in_need_view',
array('id' => $id)
)
);
这在内部重定向:
$this->forward(
'person_in_need_view',
array('id' => $id)
)
答案 1 :(得分:1)
Actualy你差不多完成了;) TL; DR 只需使用
return $this->redirectToRoute('person_in_need_view', ['id' => $yourEntity->getId()]);
我有点好奇为什么你会通过$form->get('<FIELD_NAME>)->normData()
获取数据,但是有明显的共鸣......
我希望您为PersonInNeedType
实体配置了PersonInNeed
。如果是这样,请致电
if ($form->isSubmitted() && $form->isValid()) {
/** @var PersonInNeed personInNeed **/
$personInNeed = $form->getData();
//at the end...after persist and flush so your entity is stored in DB and you have an ID
return $this->redirectToRoute('person_in_need_view', ['id' => $personInNeed->getId()]);
}