I
I
Ivashka2014-04-07 20:19:13
symfony
Ivashka, 2014-04-07 20:19:13

Symfony 2. How to save an entity passed to a form?

There is an entity "User" - represents a user in the system. There is a "Role" entity - this entity represents the user's role in the system. Between themselves they are connected "ManyToMany".

#  Часть кода из файла .../Entity/User.php которая относится к Role сущности
/**
 * @ORM\ManyToMany(targetEntity="Role", inversedBy="users")
 */
private $roles;

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

public function getRoles() {
    return $this->roles->toArray();
}

#  Часть кода из файла .../Entity/Role.php которая относится к User сущности
/**
 * @ORM\ManyToMany(targetEntity="User", mappedBy="roles")
 */
private $users;

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

/**
 * @return \Doctrine\Common\Collections\Collection 
 */
public function getUsers() {
    return $this->roles->toArray();
}

Both entities perform their duties perfectly. Now we build the user edit form:
#  Часть кода из файла .../Form/Type/UserType.php
$builder
    ->add('username', 'text')
    ->add('email', 'email')
    ->add('roles', 'entity', ['class' => 'AcmeUserBundle:Role', 'property' => 'name'])
    ->add('save', 'submit');

#  Часть кода из файла .../Controller/UserController.php
if ($form->isValid()) {
    $em->persist($user);
    $em->flush();
}

We get the form. The form has a drop-down list (select tag) "User role", where you can select any role, click save and... an error occurs:
ContextErrorException: Catchable Fatal Error: Argument 1 passed to Doctrine\Common\Collections\ArrayCollection::__construct() must be of the type array, object given, called in /Users/Gee/Sites/sirius.pro/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php on line 547 and defined in /Users/Gee/Sites/sirius.pro/vendor/doctrine/collections/lib/Doctrine/Common/Collections/ArrayCollection.php line 47

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikita Gusakov, 2014-04-07
@hell0w0rd

Show more code. Somewhere you are wrong.
Judging by the error, somewhere the system creates an ArrayCollection, which should receive an array, and your entity is fed to it

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question