0

I'm trying to have list of cities based on the region and also the birth date of a person. That is why in my code I tried to do this :

 $builder->get('region')->addEventListener(
            FormEvents::POST_SUBMIT,
            function (FormEvent $event) use ($formModifier) {
                $data = $event->getForm()->getData();

                $birthDate = $event->getForm()->getParent()->getData();

                //formModifier where I am adding the $form->add('city'...
                $formModifier($event->getForm()->getParent(), $data, $birthDate);
            }
        );

However the data I get from $event->getForm()->getParent()->getData() doesn't render the data that I want, it gets the value of the preset data instead of the submitted one.

When I do a dump of $event->getForm()->getParent() I can see that the data that I want to target is in children and that the data that it is currently sending me when I add getData() is in model data.

Symfony\Component\Form\Form {#2290 ▼
  -config: Symfony\Component\Form\FormBuilder {#2330 ▶}
  -parent: null
  -children: Symfony\Component\Form\Util\OrderedHashMap {#2329 ▶}
  -errors: []
  -submitted: false
  -clickedButton: null
  -modelData: array:2 [▶]
  -normData: array:2 [▶]
  -viewData: array:2 [▶]
  -extraData: []
  -transformationFailure: null
  -defaultDataSet: true
  -lockSetData: false
  -name: "information_salarie"
  -inheritData: false
  -propertyPath: null
}

I tried to use getChildren() but it says that it doesn't know the method. How can I access the data inside the children element ?

The birth date is in a DateTime input just before the region one. I need it so that I can get the name of the cities at the period the person was born if it's different from the current name.

Thanks a lot for your help !

1 Answer 1

2

You can't access parent data from a child event listener: form submit is started on root form that subsequently calls the submit method on all the children forms just after firing the PRE_SUBMIT event.

If you want to modify a child form based on a parent data, you can only use the PRE_SUBMIT event on the parent form.

Ex:

$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $e) {
    $data = $e->getData();
    $form = $e->getForm();

    if ($data['birth_date'] === '1900-05-01') {
        $form->add('city', CityType::class);
    }
});

Note that if you have to change type/options on an already added field, you have to remove it first.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.