用另一种方法处理表单提交


Handling form submission in another method

我想在sendAction()下面获得提交数据,但我不能。文档中的示例都是在一个方法中完成的。我在indexAction()中生成表单,在sendAction()中处理提交。

在web和Stackowerflow中都有很多例子,但由于某种原因,没有像我这样的例子,或者可能我错过了。

Thanks for the help

namespace Se'HirBundle'Controller;
use Symfony'Bundle'FrameworkBundle'Controller'Controller;
use Symfony'Component'HttpFoundation'Response;
use Symfony'Component'HttpFoundation'Request;
class EmailController extends Controller
{
    public function indexAction()
    {
        $defaultData = array('message' => 'Type your message here');
        $form = $this->createFormBuilder($defaultData)
                ->setAction($this->generateUrl('email_send'))
                ->setMethod('POST')
                ->add('name', 'text')
                ->add('email', 'email')
                ->add('message', 'textarea')
                ->add('send', 'submit')
                ->getForm();
        return $this->render('SeHirBundle:Default:email.html.twig',
                            array('page' => 'Email', 'form' => $form->createView()));
    }
    public function sendAction(Request $request)
    {
        if ($request->getMethod() == 'POST')
        {
            $name = //How to get submission data
            $email = //How to get submission data
            $message = //How to get submission data
            return new Response('Email sent');
        }
        return new Response('Form is faulty');
    }
}

也不打印任何内容:$this->get('request')->request->get('name');

当我转储$request时,我得到这个:

Symfony'Component'HttpFoundation'Request Object
(
    [attributes] => Symfony'Component'HttpFoundation'ParameterBag Object
        (
            [parameters:protected] => Array
                (
                    [_controller] => Se'HirBundle'Controller'EmailController::sendAction
                    [_route] => email_send
                    [_route_params] => Array
                        (
                        )
                )
        )
    [request] => Symfony'Component'HttpFoundation'ParameterBag Object
        (
            [parameters:protected] => Array
                (
                    [form] => Array
                        (
                            [name] => 11
                            [email] => 11@1.com
                            [message] => Type your message here
                            [send] => 
                            [_token] => NfPK_MN6oWYQm2SRrgRjoldwkrodiT033FNsXSjv3TA
                        )
                )
        )

如果您想直接从请求中提取POST数据,您可以执行$request->request->get('name')

最好的方法是创建自己的表单类,并在两个操作中使用它。一次用于生成,一次用于验证。