Symfony 3 使用 url 参数重定向到另一个路由

Symfony 3 Redirect to another routhe with url parameter

在我的 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 参数?

Link:

这使用 301 return 代码重定向到客户端:

$this->redirect(
    $this->generateUrl(
        'person_in_need_view',
        array('id' => $id)
    )
);

这在内部重定向:

$this->forward(
    'person_in_need_view',
    array('id' => $id)
)

实际上你快完成了 ;) TL;DR 只需使用

return $this->redirectToRoute('person_in_need_view', ['id' => $yourEntity->getId()]);

我有点好奇你为什么通过 $form->get('<FIELD_NAME>)->normData() 获取数据,但这可能是有原因的...

希望您已经为 PersonInNeed 实体配置了 PersonInNeedType。如果是这样,就打电话

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()]);
}