1

我在 Symfony 2 中使用带有 mongoDB 文档的表单时遇到问题。

我正在尝试使用一个表格来代表我的第一个文档(帖子),其中包含 oneToMany 到标签(参考)的关系

关系声明如下:

/**
 * @Assert\Collection
 * @MongoDB\ReferenceMany(targetDocument="Acme\ManagerBundle\Document\Tags")
 */
protected $tags;

一个标签有一个 ID 和一个名称。

我已经尝试了很多事情来使它工作

$form = $this->createFormBuilder($tag)->add('tags', 'choice', array('choices' => $tags, 'multiple' => true, 'expanded' => true, 'empty_value' => true,  ))

表单显示选项,但一旦提交,表单无效并继续显示错误:

“字段“0”、“1”、“2”不是预期的”

我也试过这个:symfony2 form selection and mongodb

但是它的使用有点令人困惑

更新

这是我提交帖子后得到的:

object(Doctrine\Common\Collections\ArrayCollection)#795 (1) {
  ["_elements":"Doctrine\Common\Collections\ArrayCollection":private]=>
  array(2) {
    [0]=>
    object(Acme\ManagerBundle\Document\Tags)#723 (2) {
      ["id":protected]=>
      string(24) "4f7a0eb1ecd111b99c3d2f25"
      ["name":protected]=>
      string(6) "Fruits"
    }
    [1]=>
    object(Acme\ManagerBundle\Document\Tags)#720 (2) {
      ["id":protected]=>
      string(24) "4f7a0ec7ecd111b99c3d2f26"
      ["name":protected]=>
      string(10) "Vegetables"
    }
  }
}

所以现在我明白为什么我有“字段“0”、“1”、“2”不是预期的”,但我不明白为什么 Symfony 不处理它。

我一直在寻找可能的捆绑包,但什么也没有

我不知道如何有一个很好的形式来滋润我的对象和相关对象,有没有人有这个问题的解决方案或其他想法来解决这个问题?

非常感谢!

4

2 回答 2

0

在没有看到所涉及的数据的情况下,我只能在这里做出最好的猜测。

感觉你的代码行应该是这样的。

$tags = $post->getTags();

$fixedTags = array();
foreach ($tags as $tag) {
    $fixedTags[$tag->getId()] = $tag->getName();
}

$form = $this->createFormBuilder($post)
    ->add(
        'tags', 
        'choice', 
        array(
            'choices' => $fixedTags,
            'multiple' => true,
            'expanded' => true,
            'empty_value' => true
        )
    );

现在我认为正在发生的事情是您正在以这样的形式获取您的 $tags 数据。

array(0 => (Object)Tag, 1 => (Object)Tag, 2 => (Object)Tag)

你真正想要的可能是这样的。

array('topic1' => 'Topic 1', 'topic2' => 'Topic 2', 'topic3' => 'Topic 3')

如果您不是这种情况,请回复一些数据输出,我相信我们将能够提供更多帮助。

于 2012-03-31T20:43:26.713 回答
0

choice默认情况下不会保存字段(尽管您可以在提交表单时手动保存)。您需要查看公认没有很好记录的类型,但它与此处document的类型基本相同。entity

没想到是3年前的!好吧,我猜它就在这里,以防其他人找到这个页面。

于 2015-10-01T18:05:25.210 回答