In one of my custom form types I need to add a custom HTML attribute to the field. However that attribute is based on the data. So I added an event handler but I'm not sure what I should do in it.
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
$data = $event->getData();
// not sure what to do here.
};
Maybe it should be done somewhere else. Please keep in mind that for my use case I need the data initially set to the form, not the submitted data.
EDIT: I've been asked for some more details of what I'm trying to achieve. Basically I need to put the initial data from database (which are available in the PRE_SET_DATA event) into a data-*
HTML attribute so that javascript could use it.
UPDATE: Even after several months there is no good answer so I assume it is currently impossible to solve this.
You can replace your old form-element with new one:
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
$data = $event->getData();
$form = $event->getForm();
$val = $data['some_field'];
$options = $form->get('existing_field_name_to_replace')->getConfig()->getOptions();
$options['attr']['your-attr'] = $val;
$form->add('existing_field_name_to_replace', 'type', $options);
};
$form->add()
replaces previously defined form field. But you can also use $form->remove()
and then $form->add()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With