【问题标题】:Symfony form CollectionType FieldSymfony 表单 CollectionType 字段
【发布时间】:2017-01-15 06:13:53
【问题描述】:

您好,我是 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->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,没有帮助。

非常感谢。

【问题讨论】:

    标签: php forms symfony collections


    【解决方案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 文档已经很完美了:)

    但我假设你已经有一个 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()

    【讨论】:

    • 像魅力一样工作。不知道我必须在 UserType 中添加语言。非常感谢,你是我的救命恩人。
    猜你喜欢
    • 2016-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多