2017-02-01 56 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

    相关问题