Reputation: 5830
When a form doesn't validate, I need to access the submitted data inside a Form Class in order I can set some options in a custom field.
I have tried with
$data = $builder->getForm()->getData();
$data = $builder->getData();
but $data
has the empty object. So... what is the correct form to access the submitted data by the user after validation error in the form class?
Thanks
Upvotes: 2
Views: 2101
Reputation: 31919
For those who wonder how Form Events are used.
Here is an example where you can modify the form after the user has tapped the submit button.
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormEvent;
// ...
/* Listener to order to set a price if it does not exist yet */
$builder->get('price')->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
$data = $event->getData();
// modify it as you wish
$event->setData($data);
});
The FormEvents::PRE_SUBMIT event is dispatched at the beginning of the Form::submit() method.
If needed, here is an example where you can modify the form price
before you display it.
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormEvent;
// ...
/* Listener to order to set a price if it does not exist yet */
$builder->get('price')->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
$data = $event->getData();
if (null === $data) { $data = '0.00'; }
$event->setData($data);
});
The FormEvents::PRE_SET_DATA event is dispatched at the beginning of the Form::setData() method.
Upvotes: 0
Reputation: 4685
Look into $options variable (var_dump it)
As I remeber you are looking for
$options['data']
Upvotes: 0
Reputation: 5864
The problem is you're trying to access submitted data when it has not be handled yet. Basically, when you are in a builder (buildForm
for the abstract types), you are building your form structure. It has nothing to do with form submission/binding. This is why you get the initial data when you call $builder->getData()
because it only know the initial data at this state.
Knowing that the form component allows you to access the submitted data via events. You can attach a listener to your builder and rely on one of the *_submit
event. The FormEvent class will given you the submitted data with $event->getData()
.
See this doc for more information: http://symfony.com/doc/current/cookbook/form/dynamic_form_modification.html
Upvotes: 4