2017-01-03 23 views
0

我想創建一個表單,用於通過用戶名搜索配置文件,然後重定向到用戶的配置文件頁面。順便說一下,我使用Symfony 3.2。如何使Symfony GET表單重定向到使用參數進行路由?

我認爲這樣做的自然方式是GET操作表單。它甚至可以讓客戶直接用好用戶名來更改網址以查看其個人資料。

這裏是我的控制器代碼:

ProfileController.php

//... 

/** @Route("/profil/search", name="profil_search") */ 
public function searchAction() {   
    $builder = $this->createFormBuilder(); 
    $builder     
     ->setAction($this->generateUrl('profil_show')) 
     ->setMethod('GET') 
     ->add('username', SearchType::class, array('label' => 'Username : ')) 
     ->add('submit', SubmitType::class, array('label' => 'Search')); 
    $form = $builder->getForm(); 

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

/** @Route("/profil/show/{username}", name="profil_show") */ 
public function showAction($username) {  
    $repository = $this->getDoctrine()->getRepository('AppBundle:User'); 
    $searchedUser = $repository->findOneByUsername($username); 

    return $this->render('profils/profil_show.html.twig', [ 
     'searchedUser' => $searchedUser, 
    ]); 
} 

//... 

此代碼將導致以下錯誤消息:

一些強制性的參數丟失( 「用戶名」)來生成 路由「profil_show」的URL。

我仔細閱讀documentation但猜不到,我怎麼能傳遞username變量的profil_show路徑作爲參數?

如果我的做法不是很好,謝謝你在評論中告訴我,但我仍然想知道如何使用GET表單。

編輯:

感謝@MEmerson回答,我現在明白了。因此,對於像我這樣的未來的菜鳥,這裏是我是如何做的:

/** @Route("/profil/search", name="profil_search") */ 
public function searchAction(Request $request) {  
    $data = array(); 
    $builder = $this->createFormBuilder($data); 
    $builder     
     //->setAction($this->generateUrl('profil_show')) 
     //->setMethod('GET') 
     ->add('username', SearchType::class, array('label' => 'Username : ')) 
     ->add('submit', SubmitType::class, array('label' => 'Search')); 
    $form = $builder->getForm(); 

    $form->handleRequest($request); 
    if ($form->isSubmitted() && $form->isValid()) { 
     $data = $form->getData(); 
     return $this->redirectToRoute('profil_show', array('username' => $data["username"])); 
    } 

    return $this->render('profils/profil_search.html.twig', [ 
     'method' => __METHOD__, 
     'form' => $form->createView(), 
     'message' => $message, 
    ]); 
} 

回答

1

如果你看看錯誤信息是說,問題出在哪裏,你試圖生成路徑「profil_show」網址。

你的控制器標註要求該URL的用戶名

/** @Route("/profil/show/{username}", name="profil_show") */ 

這意味着,Symfony的期待http://yoursite.com/profil/show/username的路線來填充。但是,如果你想要把它作爲一個GET形式張貼真的應該期待http://yoursite.com/profil/show?username

您可以添加第二個路徑或更改現有的路線是

/** @Route("/profil/show", name="profil_show_search") */ 

應該解決您的問題。

+0

謝謝,我現在明白了。我認爲GET方法可以重定向到路由,就像在第一個鏈接中一樣。然後我會堅持使用POST,然後在控制器中重定向。 –

相關問題