p3tch p3tch - 1 month ago 12
Twig Question

Symfony - Why does my form get every answer that exists in the table?

This isn't so much an issue but rather something I noticed and would like to better understand.

I have a

Poll
class which has a collection of
votes
and
pollOptions
.
My
PollOption
class has the
poll
it belongs to and a
title
.
The
Vote
class also has the
poll
it belongs to, as well as its own collection of
voteChoices
and
user
.
The
VoteChoice
class has the
vote
it belongs to, the
answer
(
PollOption
) that the vote is for, and a
priority
.

I have a form that contains a collection of forms (a
Vote
with many
VoteChoice
)

The
VoteChoiceType
is as follows

class VoteChoiceType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('answer', null, array('disabled' => true))
->add('priority', null);
}

public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'PollBundle\Entity\VoteChoice',
));
}
}


Now in my
VoteController
I create and populate a
Vote
with many
voteChoices
, setting the
answer
according to the available choices for the current poll (derived from the URL)

$vote = new Vote();
$vote->setPoll($poll);
foreach ($vote->getPoll()->getPollOptions() as $op) {
$vc = New VoteChoice();
$vote->addVoteChoice($vc->setAnswer($op));
}


So my twig is as follows

<ul class="voteChoices" data-prototype="{{form_widget(form.voteChoices.vars.prototype)|e('html_attr') }}">
{% for voteChoice in form.voteChoices %}
<li>{{ voteChoice.vars.value.answer }} {{ form_row(voteChoice.priority) }}</li>
{% endfor %}
</ul>
</div>
<p><button type="submit" class="btn btn-success">Go!</button></p>
{{ form_end(form) }}


However, if I enable
answer
in my
VotechoiceType
and in my twig include
{{ form_row(voteChoice.answer) }}
I notice that all my poll options from the table as in the selectable list, even if they are apart of another poll.

Why is this? How would I get it to just display options available form the poll the vote belongs to instead? My suspicion is I've not handled the relationship between the
VoteChoice
and
PollOption
correctly (many to one). If I've made a mistake here, I've likely done it elsewhere (eg a
Poll
might be getting every
Vote
in the db rather than the ones that belong to it)

Answer
$builder->add('answer', null, array('disabled' => true))

creates a ChoiceType-Field for PollOption and by default it populates it with all PollOption. There is nothing limiting the Choice-Field because your form doesn't know about the desired limitation given through $voteChoice->getVote()->getPolloptions().

Take a look at Symfonys EntityType Field: The query_builder option might give you a way to solve your issue, by adding a custom query to the answer-field, which selects to correct subset of PollOptions through the VoteChoice -> Vote -> Polloptions relation.