3

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 1

6

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);
    }
);
Sign up to request clarification or add additional context in comments.

4 Comments

It seems like the Validator component also runs in POST_SUBMIT, so aren't you risking having this data set AFTER validations have run?
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.
Is there anything special to take care of, when registering this special event listener? It seems like POST_SUBMIT is never called for me (Symfony 3.3).
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()’)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.