我有一个index
页面,其中包含一个简单的表单;如果表单验证失败,则会重新加载索引页面,如果没有,则与页面相关的操作会将请求转发给与页面success
相关的其他操作。 success
页面使用提交的表单从DB创建列表。一旦我们进入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()));
}
虽然上述实施"工作"我有几个问题:
当我提交第一个表单时,网址保持不变,第一页的表单如下:
[HOST] /app_dev.php?place=London&Date = ......
但是,如果我提交第二个表单,则URL正确: [HOST] /app_dev.php/success?place=London&date = .....
答案 0 :(得分:0)
提交表单后,它会使用相同的控制器和操作进行访问。您必须处理提交的数据,然后重定向到成功页面。
所以在你的例子中:
if($form->isSubmitted() && $form->isValid()) {
...
...
return $this->redirectToRoute('eventList');
}
如果您需要从一个"页面转移发布的数据"到另一个,然后你必须将它存储在会话$this->get('session')->set('name', val);
中,然后通过$this->get('session')->get('name');
更多信息如何在Symfony中处理会话:https://symfony.com/doc/current/controller.html#the-request-object-as-a-controller-argument