Frager. Frager. - 1 year ago 150
PHP Question

Symfony form CollectionType Field

Hi I'm quite new in Symfony 2. I'm dealing with this problem for several hours by now, so I'm forced to ask comunity.

I have two Entities

User --> Language (OneToMany)

User Entity

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

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


User_Language Entity

/** @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' );
}


I'm trying to build a form where user can add/edit/delete his speaking languages

User_Language in Database

User_language

When getting data from database (in controller) -
with $user->GetLanguages() I got persistantCollection,
with QueryBuilder() I got an array

Is there any way, how to pass this into CreateForm() function?

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


I'm getting this two erros:

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.


or

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.


Setting
'data_class' => null
, did not help.

Thanks a lot.

Answer Source

If you want to allow your user to add/delete any number of languages, you have to use a collection type field. http://symfony.com/doc/2.7/reference/forms/types/collection.html

Here to use it: http://symfony.com/doc/2.7/form/form_collections.html

You create a form for the user entity, you add the collection field type on your User_languageType, and you have to add some javascript to manage adding and deleting language.

I don't write all the example, the symfony doc is already perfect for that :)

But I assume you already have a Form/userType, you can add the collection field :

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

(for symfony3)

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

The array short syntaxe [] needs php5.4 min, if not use array()