如何使用 submit() 函数处理表单提交
有了 handleRequest() 方法,处理表单提交就简单多了:
use Symfony\Component\HttpFoundation\Request;
// ...
public function newAction(Request $request)
{
$form = $this->createFormBuilder()
// ...
->getForm();
$form->handleRequest($request);
if ($form->isValid()) {
// perform some action...
return $this->redirectToRoute('task_success');
}
return $this->render('AcmeTaskBundle:Default:new.html.twig', array(
'form' => $form->createView(),
));
}
有关这个方法的更多细节详见处理表单提交。
手动调用 Form::submit()
在 Symfony 2.3 之前,submit() 方法叫做 bind()。
use Symfony\Component\HttpFoundation\Request;
// ...
public function newAction(Request $request)
{
$form = $this->createFormBuilder()
// ...
->getForm();
if ($request->isMethod('POST')) {
$form->submit($request->request->get($form->getName()));
if ($form->isValid()) {
// perform some action...
return $this->redirectToRoute('task_success');
}
}
return $this->render('AcmeTaskBundle:Default:new.html.twig', array(
'form' => $form->createView(),
));
}
向 Form::submit() 传递一个请求(不赞成)
在 Symfony 2.3 之前,submit 方法叫做 bind。
use Symfony\Component\HttpFoundation\Request;
// ...
public function newAction(Request $request)
{
$form = $this->createFormBuilder()
// ...
->getForm();
if ($request->isMethod('POST')) {
$form->submit($request);
if ($form->isValid()) {
// perform some action...
return $this->redirectToRoute('task_success');
}
}
return $this->render('AcmeTaskBundle:Default:new.html.twig', array(
'form' => $form->createView(),
));
}