2017-02-01 59 views
1

我有一個index頁面,其中包含一個簡單的形式;如果表單驗證失敗,那麼索引頁會重新加載錯誤,否則與頁面相關的操作會將請求轉發給與頁面success相關的另一個操作。 success頁面使用提交的表單從數據庫創建一個列表。一旦我們在success頁面上,我們有另一種類似於用戶可以用來修改頁面上的列表的第一種形式。兩種形式都有相同的字段。這是處理兩頁中表單的正確方法嗎?

  • 索引頁行動:

    class DefaultController extends Controller { 
    
    /** 
    * @Route("/", name="homepage") 
    */ 
    public function indexAction(Request $request) { 
    
        $event = new Event(); 
        $form = $this->createForm(EventForm::class, $event); 
        $form->handleRequest($request); 
    
        if($form->isSubmitted() && $form->isValid()) { 
    
         // Do some minor modification to the form data 
         $event->setDate($party->getDate()->modify('+12 hours')); 
         $cityName = strtolower($event->getPlace()['city']); 
    
         // We know the form data is valid, forward it to the action which will use it to query DB 
         return $this->forward('AppBundle:Frontend/Default:eventsList', array('request' => $request)); 
    
        } 
    // If validation fails, reload the index page with the errors 
    return $this->render('default/frontend/index.html.twig', array('form' => $form->createView())); 
    } 
    
  • 成功頁面的動作(如該表格數據被轉發)

    /** 
        * @Route("/success", name="eventList") 
        */ 
    public function eventsListAction(Request $request) { 
    $event = new Party(); 
    // Create a form in the second page and set its action to be the first page, otherwise form submition triggers the FIRST action related to page index and not the one related to page success 
    $form = $this->createForm(EventForm::class, $event, array('action' => $this->generateUrl('eventList'))); 
    $form->handleRequest($request); 
    
    if($form->isSubmitted() && $form->isValid()) { 
        $event->setPlace($form["place"]->getData()); 
        $event->setTitle($form["title"]->getData()); 
    
        $repository = $this->getDoctrine() 
         ->getRepository('AppBundle:Event'); 
    
        // .... 
        // Create a list of events using the data from DB 
        // .... 
    
        return $this->render('default/frontend/success.html.twig', 
         array('events' => $events, 'form' => $form->createView()) 
        ); 
    } 
    
    return $this->render('default/frontend/success.html.twig', array('form' => $form->createView())); 
    } 
    

雖然以上實施的 「作品」 我有一個幾個問題:

  1. 當我提交了第一種形式的網址保持不變,即第一頁的一樣:

    [主持人] /app_dev.php?place=London &日期= ......

但是,如果我提交第二形式的URL是正確: [HOST] /app_dev.php/success?place=London &日期= .....

  • 實現對我來說很難受,有沒有更好的方法來實現這是嗎?
  • 回答

    0

    當表單被提交時,它使用相同的控制器和操作進行處理。您必須處理子數據,然後重定向到成功頁面。

    所以,在你的榜樣:

    if($form->isSubmitted() && $form->isValid()) { ... ... return $this->redirectToRoute('eventList'); }

    如果你需要從一個「頁」傳遞發佈的數據到另一個,則必須將其存儲在會話$this->get('session')->set('name', val);,然後在檢索會話數據eventList動作$this->get('session')->get('name');

    更多信息如何處理Symfony中的會話:https://symfony.com/doc/current/controller.html#the-request-object-as-a-controller-argument

    相關問題