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

时间:2014-05-26 13:45:56

标签: php symfony

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

在网络和Stackowerflow上有很多例子,但由于某些原因,没有像我这样的例子,或者我错过了。

感谢您的帮助

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
                        )

                )

        )

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

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