繁体   English   中英

Symfony 2.3 handleRequest($ request)没有设置实体

[英]Symfony 2.3 handleRequest($request) doesn't set entity

我有联系实体,使用以下方法进行通话:

postContactAction(Request $request)

使用app/console generate:doctrine:form BundleName:Contact

在post函数中,尝试获取请求并将实体设置为请求名称,电子邮件等参数:

$contact = new Contact();
$form = $this->createForm(new ContactType(), $contact, array(
    'method' => 'POST'));
$form->handleRequest($request);

并且在检查时, var_dump($contact); 返回值为空的字段。

可能是什么问题?

使用邮递员发送发帖请求,它无需表格即可工作。

在ContactType中:

public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name', 'text')
            ->add('email', 'text', array('required' => false))
            ->add('phone', 'integer', array('required' => false))
            ->add('text', 'textarea')
            ->add('subject', 'text')
            ->add('createdAt', 'datetime', array('required' => false))
        ;
    }

在ContactController中:

public function postContactAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $this->initErrorContainer();
        $validator = $this->get('validator');

        $contactDetails = $this->getRequest()->request->all();

        // check if email and phone exists or not. One is enough
        if (!array_key_exists('email', $contactDetails) && !array_key_exists('phone', $contactDetails)) {
            $this->errorContainer->createAndAdd('email', $this->errorContainer->MESSAGE_REQUIRED);
            $this->errorContainer->createAndAdd('phone', $this->errorContainer->MESSAGE_REQUIRED);
            return $this->getView();
        }

        $contact = new Contact();

        // handle form
        $form = $this->createForm(new ContactType(), $contact, array(
            'method' => 'POST'));
        $form->handleRequest($request);

        // set default values
        var_dump($contact);
        die;

很奇怪,但是您可以在调用createForm之后尝试获取表单,看看是否有相关的东西,即:您拥有:

$form = $this->createForm(new ContactType(), $contact, array('method' => 'POST'));

然后只需添加:

$form = $this->createForm(new ContactType(), $contact, array('method' => 'POST'))->getForm();

解决了。 由于实体使用与请求不同的类型,因此您只需创建该实体的简单模型,使用handleRequest将请求字段设置为该实体类型,然后就可以使用它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM