Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony/Form add attribute based on the data

Tags:

php

symfony

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.

like image 534
enumag Avatar asked Feb 02 '16 14:02

enumag


1 Answers

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().

like image 184
Michael Sivolobov Avatar answered Oct 11 '22 00:10

Michael Sivolobov