Symfony表单CollectionType字段

时间:2016-09-07 13:54:15

标签: php forms symfony collections

嗨,我在Symfony 2中很新。我现在已经处理好这个问题几个小时了,所以我不得不问社区。

我有两个实体

用户 - >语言(OneToMany)

用户实体

/**
 * 
 * @ORM\OneToMany(targetEntity="User_Language", mappedBy="user")
 */
private $languages;

public function __construct() {
    $this->languages = new ArrayCollection();
}

User_Language实体

/** @ORM\Column(type="string", length=50) */
private $language;

/**
 * @ORM\ManyToOne(targetEntity="User", inversedBy="languages")
 */
private $user;

User_LanguageTyp

public function buildForm(FormBuilderInterface $builder, array $options) {

    $builder
        ->add( 'language' );
}

我正在尝试构建一个用户可以添加/编辑/删除他的说话语言的表单

数据库中的User_Language

User_language

从数据库获取数据时(在控制器中) - 使用$ user-> GetLanguages()我得到了persistantCollection, 使用QueryBuilder()我得到了一个数组

有什么办法,如何将其传递给CreateForm()函数?

$form = $this->createForm( User_LanguageType::class, $user->getLanguages() );

我得到了这两个错误:

The form's view data is expected to be an instance of class ArpanetRuzicja7EstatesBundle\Entity\User_Language, but is an instance of class Doctrine\ORM\PersistentCollection.

The form's view data is expected to be an instance of class ArpanetRuzicja7EstatesBundle\Entity\User_Language, but is a(n) array. You can avoid this error by setting the "data_class" option to null or by adding a view transformer that transforms a(n) array to an instance of ArpanetRuzicja7EstatesBundle\Entity\User_Language.

设置'data_class' => null,没有帮助。

非常感谢。

1 个答案:

答案 0 :(得分:1)

如果要允许用户添加/删除任意数量的语言,则必须使用集合类型字段。 http://symfony.com/doc/2.7/reference/forms/types/collection.html

在这里使用它: http://symfony.com/doc/2.7/form/form_collections.html

您为用户实体创建表单,在User_languageType上添加集合字段类型,并且您必须添加一些javascript来管理添加和删除语言。

我没有写完所有的例子,symfony doc已经完美了:)

但我假设你已经有了Form / userType,你可以添加收集字段:

->add('tags', 'collection', [
        'type'         => New User_LanguageType(),
        'allow_add'    => true,
        'allow_delete' => true,
    ]);

(对于symfony3)

->add('tags', 'collection', [
        'type'         => User_LanguageType::class,
        'allow_add'    => true,
        'allow_delete' => true,
    ]);

数组短语法[]需要php5.4分钟,如果不使用array()