Symfony Embed Forms PRE_SET_DATA access parent form field data

  doctrine-orm, php, symfony

i have a InspectionPlan Form Type which has a product EntityType field, (Products can have attributes i assign some by fixtures) however, the formtype also has a CollectionType Field for another entity called InspectionPlanSections, this uses a InspectionPlanSectionFormType which has a CollectionTypeField for an entity called InspectionPlanQuestions with a InspectionPlanQuestionFormType with allow_add’ => true and a prototype, these questions have a relation to the earlier mentioned ProductAttributes, , only the product attributes the earlier submittet Product has should be assignable

class InspectionPlanQuestionType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {

        $builder
        ->add('question', TextareaType::class, [
            'attr' => ['class' => 'tinymce']   ])
        ->add('productAttribute', EntityType::class, [
            'class' => ProductAttribute::class,
            'placeholder' => 'Attribut auswählen',
            'choice_label' => 'name'
        ]);

    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'data_class' => InspectionPlanQuestion::class,
        ]);
    }
}

this loads all product attributes which is not exactly what i want

class InspectionPlanQuestionType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder->add('question', TextareaType::class, [
            'attr' => ['class' => 'tinymce']   ]);
        $builder->addEventListener(FormEvents::PRE_SET_DATA,
            function (FormEvent $event)
            {
                $form = $event->getForm();
                $child = $event->getData();
                if ($child) {
                    $form->add('productAttribute', ChoiceType::class, [
                        'placeholder' => 'forms.product.attribute_placeholder',
                        'choices' => $child->getInspectionPlanSection()->getInspectionPlan()->getProduct()->getProductAttributes(),
                        'choice_label' => function ($choice, $key, $value) {
                           return $choice->getName();
                        },
                    ]);
                }
            }
        );
    }

this gives me the desired attributes in the select, but only after i atleast submitted one section with a question, because if none were submitted, the $event->getData() returns always null

so when i create a fresh InspectionPlan and add a product, submit the form, and then add a Section and questions via javascript, i get no product attributes select field rendered in my question field

Can someone explain me why this works, after i submitted at least one question?

Source: Symfony Questions

LEAVE A COMMENT