2

我完全陷入了 Symfony Forms 和 Doctrine MongoDb 的结合中,需要你的帮助。

我有一个带有@EmbedMany 和@Hash 的用户类:

/**
 * @MongoDB\Document
 */
class User
{
    /**
     * @MongoDB\EmbedMany(targetDocument="Project", strategy="set")
     */
    protected $projects;

    /**
     * @MongoDB\Hash
     */
    protected $schedule;
}

项目类:

/**
 * @MongoDB\Document
 */
class Project
{
    /**
     * @MongoDB\Id
     */
    protected $id;

    /**
     * @MongoDB\String
     */
    protected $name;
}

通过 Doctrine Document Manager 保存新记录后,我得到了以下结构:

{
   "_id": "1",
   "projects": [
     {
       "_id": ObjectId("50d1c5116146a13948000000"),
       "name": "Project 1"
     },
     {
       "_id": ObjectId("50d069336146a10244000000"),
       "name": "Project 2"
     }
   ],
   "schedule": ["2012-12-01", "2012-12-04"]
}

还有 2 个集合 - 项目和时间表,充满了数据。

当我尝试编辑用户时,我想显示一个带有 2 个复选框列表的表单,其中包含来自这些集合的数据和用户拥有的选定项目。像这样:

例子

问题是如何为@Embed 和@Hash 属性构建这样的表单?

我尝试了不同的方法:

class UserFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('schedule', 'collection', array(
            'type' => 'choice',
            'options'  => array(
                'expanded' => true,
                'multiple' => true,
            ),
        ));
        $builder->add('projects', 'document', array(
            'class' => 'Acme\MyBundle\Document\Project',
            'property' => 'name',
        ));
    }

    public function getDefaultOptions(array $options)
    {
        return array('data_class' => 'Acme\MyBundle\Document\User');
    }
}

或者

 $builder->add('schedule', 'choice', array(
        'expanded' => true,
        'multiple' => true,
 ));
 $builder->add('projects', 'collection', array(
        'type' => 'choice',
        'options'  => array(
            'expanded' => true,
            'multiple' => true,
        ),
 ));

其中一些失败并出现错误:Expected argument of type "array", "string" given。有些产生了成功的表单渲染,但列表中没有选定的项目。

也许我应该使用自定义数据转换器或手动呈现这些控件......

4

2 回答 2

1

要使用嵌入文档,必须将嵌入文档注释为 EmbeddedDocument,而不是 Document。但是,看起来您实际上希望在用户文档中的项目注释上使用 ReferenceMany;从嵌入文档列表中选择是没有意义的,除非您说选择要删除的文档。

于 2013-02-04T17:32:58.500 回答
0

我解决了@Hash 问题。考虑到数字索引数组,应该使用 @Collection 注释。

$builder->add('schedule', 'choice', array(
        'choices' => <your choices list here>,
        'expanded' => true,
        'multiple' => true,
));

@EmbedMany 问题仍然存在。

于 2012-12-22T10:58:38.247 回答