Jesse
Jesse

Reputation: 889

Symfony2 Form with collection type (many-to-many)

What I have

I have a database table "Teams" and a table "Players", connected with a Teams_has_Players table (many-to-many relationship). I generated my entities. I can now succesfully retrieve the players from a team by doing: $players = $team->getPlayers()->toArray();

What I'm trying to do

I'm trying to make a form where you can edit all of the team's player names and their position on the field. So I basically would like to have some rows with in each row an input field with the name and an input field with his location.

What I tried to do

So I read a lot about the Symfony2 Collection type and tried this:

$form = $this->createFormBuilder(null)
    ->add('name', 'text', array('label' => 'Name', 'data' => $team->getName()))
    ->add('players', 'collection', array('data' => $team->getPlayers()->toArray()))
    ->getForm();

In my view I tried this:

<ul>
    {% for player in form.players %}

        <li>
            {{ form_widget(player.name) }}{{ form_widget(player.position) }}
        </li>
    {% endfor %}
</ul>

But I get this error:

The form's view data is expected to be of type scalar, array or an instance of \ArrayAccess, but is an instance of class MatchTracker\Bundle\AppBundle\Entity\Players. You can avoid this error by setting the "data_class" option to "MatchTracker\Bundle\AppBundle\Entity\Players" or by adding a view transformer that transforms an instance of class MatchTracker\Bundle\AppBundle\Entity\Players to scalar, array or an instance of \ArrayAccess.

So I added 'data_class' => 'MatchTracker\Bundle\AppBundle\Entity\Players', but then I get an error that The form's view data is expected to be an instance of class MatchTracker\Bundle\AppBundle\Entity\Players, but is a(n) array. You can avoid this error by setting the "data_class" option to null

Anyone that can help me solve this problem? I just want to edit the team's player names/locations/.. in a form. If that works I'm going to extend the form so I can add/remove players.

Upvotes: 1

Views: 5474

Answers (1)

Related Questions