I have an evaluation that has different questions (items) and each item has a specific number of possible choices.
I need to pass the number of choices and the labels of each question to build the form for each item (question).
I can pass variables from the "parent" form to the form collection but I can't figure out how to pass a variable that is specific to each iteration in the Evaluation "answers" property.
In my controller:
$evaluation = new Evaluation();
$answers = array();
// i set each answer to default 0, for the form to place them in view
foreach ($items as $index => $item) {
$answers[$index] = array('value' => 0, 'item_id' => $item->getId());
}
$evaluation->setAnswers($answers);
$formBuilder = $this->createFormBuilder($evaluation);
$formBuilder->add("answers", CollectionType::class, array(
'entry_type' => AnswerType::class,
//here i pass all the items objects array to the AnswerType form.
'entry_options' => array(
'items' => $items,
),
'allow_delete' => false,
'allow_add' => false,
));
And than in the AnswerType form class:
class AnswerType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$choices = array();
// here I have all the items available in $options['items'];
// but each item has a specific number of choices, and I need the current one that is being built
// and I also need other info form the item like the question it self
for($i = 1; $i <= $current_item_number_of_choices_that_i_dont_have;$i++){
$choices[$i] = $i;
}
$builder->add('value', ChoiceType::class, array(
'choices_as_values' => true,
'multiple'=>false,
'expanded'=>true,
'choices' => $choices,
'label' => $current_item_text_label_that_I_also_need
));
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'items' => null
));
}
}
Thanks! :)