Is it possible to use Data transformers to merge (n) fields in a form into one persistable field? If it's possible, how to do it? The cookbook only gives an example to transform one piece of data into another type, but I need to be able to dump N fields into only one for persistence. So if I'm showing 6 fields in the form, only 3 are real fields in DB table, first and second fields are to persisted as is, but the remaining 4 fields are to be store in the third table column.
1 Answer
You should do it via FormEvent::POST_SUBMIT event.
http://symfony.com/doc/current/cookbook/form/dynamic_form_modification.html
Basically, something like this:
$builder->addEventListener(FormEvents::POST_SUBMIT, function(FormEvent $event) {
$form = $event->getForm();
// entity or array
$data = $event->getData();
// get data directly from form
$concatData = $form->get('non_mapped_field1_1')->getData() . ',' . $form->get('non_mapped_field1_2')->getData();
// assumig that data is entity class
$data->setSomeField($concatData);
}
);
4 Comments
Brian
It seems like the Validator component also runs in
POST_SUBMIT, so aren't you risking having this data set AFTER validations have run?Jovan Perovic
That is possible, but I believe (not 100% sure) that this happens first because event listener is being added in the earliest phase of form building.
Jovan Perovic
make sure that you registered the event on a form (not a field). And, silly enough, make sure that you submit the form (‘submit()’ or ‘handleRequest()’)