Symfony 2 Forms和Doctrine Mongo - 如何呈现@Embed和@Hash属性?

时间:2012-12-19 16:19:39

标签: php symfony doctrine-orm symfony-forms doctrine-odm

我完全陷入了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个复选框列表的表单,其中包含来自这些集合的数据和用户拥有的所选项目。 像这样:

Example http://img607.imageshack.us/img607/8369/formj.png

问题是如何为@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。有些产生了成功的表单渲染,但列表中没有选定的项目。

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

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

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

@EmbedMany问题仍然存在。