1

在我的 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使用路由名称重定向和传递参数?

4

2 回答 2

4

实际上你几乎完成了;) 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()]);
}
于 2017-05-13T11:36:48.193 回答
3

链接

这使用 301 返回码重定向到客户端:

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

这在内部重定向:

$this->forward(
    'person_in_need_view',
    array('id' => $id)
)
于 2017-05-13T11:34:24.967 回答