概述 快速入门 教程 手册 最佳实践 组件 参考 贡献

发布于 2015-08-27 16:50:18 | 143 次阅读 | 评论: 0 | 来源: 网络整理

2.3 新版功能: The handleRequest() method was introduced in Symfony 2.3.

With the handleRequest() method, it is really easy to handle form submissions:

use SymfonyComponentHttpFoundationRequest;
// ...

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(),
    ));
}

小技巧

To see more about this method, read 表单提交的处理.

Calling Form::submit() manually

2.3 新版功能: Before Symfony 2.3, the submit() method was known as bind().

In some cases, you want better control over when exactly your form is submitted and what data is passed to it. Instead of using the handleRequest() method, pass the submitted data directly to submit():

use SymfonyComponentHttpFoundationRequest;
// ...

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(),
    ));
}

小技巧

Forms consisting of nested fields expect an array in submit(). You can also submit individual fields by calling submit() directly on the field:

$form->get('firstName')->submit('Fabien');

Passing a Request to Form::submit() (Deprecated)

2.3 新版功能: Before Symfony 2.3, the submit method was known as bind.

Before Symfony 2.3, the submit() method accepted a Request object as a convenient shortcut to the previous example:

use SymfonyComponentHttpFoundationRequest;
// ...

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(),
    ));
}

Passing the Request directly to submit() still works, but is deprecated and will be removed in Symfony 3.0. You should use the method handleRequest() instead.

最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务