簡體   English   中英

Symfony表單CollectionType字段

[英]Symfony form CollectionType Field

嗨,我是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並沒有幫助。

非常感謝。

如果要允許用戶添加/刪除任意數量的語言,則必須使用集合類型字段。 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,可以添加collection字段:

->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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM