Symfony 3子表单作为数组而不是实体提交

时间:2017-06-22 11:16:30

标签: php forms symfony symfony-3.1

我正在将项目从Symfony 2转换为Symfony 3并遇到了问题。我有一个Event实体,它有一个TwitterSearch实体,由Event.php中的以下内容定义:

   /**
    * @ORM\ManyToOne(targetEntity="TwitterSearch", cascade={"persist"})
    * @ORM\JoinColumn(name="twitter_search_id", referencedColumnName="id")
    */
    private $twitterSearch;

这就是我在EventType中设置关系的方式:

    $builder->add('twitterSearch', TwitterSearchType::class, array(
        'required'=>false,
    ));

以下是控制器提交表单时的代码:

    $entity = new Event();
    $form = $this->createCreateForm($entity);
    $form->handleRequest($request);

    if ($form->isValid()) { 
       $entity = $form->getData();
       $em = $this->getDoctrine()->getManager();
       $em->persist($entity);
       $em->flush();
    }

这曾经在Symfony 2中工作,但现在提交表单时会抛出以下错误:

Expected value of type "TwitterSearch" for association field "Event#$twitterSearch"
, got "array" instead.

我调试了事件的代码和twitterSearch属性和数组。有谁知道为什么它不再将其转换为TwitterSearch的实例?

1 个答案:

答案 0 :(得分:1)

改为使用EntityType

示例:

$builder->add('twitterSearch', EntityType::class, array(
    'class' => TwitterSearch::class,
    'choice_label' => 'name',
));