0

This is an existing schema I'm working with and I'm trying to not make any changes for the time being. I have an entity property that represents a university semester, like "fall12", "spring11", etc.

When adding or editing this entity with a form, I want to split that property into two form fields: "Season" (fall or spring") and "Year" (2011, 2012, etc):

...
->add('formSemesterSeason', 'choice', array(
    'label' => 'Season',
    'mapped' => false,
    'choices' => array('fall' => 'Fall', 'spring' => 'Spring'),
))
->add('formSemesterYear', 'choice', array(
    'label' => 'Year',
    'mapped' => false,
    'choices' => $this->courseManager->getYearChoices(),
))
...
  1. When submitting the form, the values need to be combined and saved to the "semester" property on the entity as a string
  2. When viewing the edit form, the existing "semester" value needs to be split between the two.

I don't think data transformers help here, since they apply to transforming just one form item.

Right now I'm using a form event POST_SET_DATA to fill out the two form fields when editing an existing entity:

$builder->addEventListener(FormEvents::POST_SET_DATA, function (FormEvent $event) use ($course_manager) {
    $course = $event->getData();
    $form = $event->getForm();

    $semester = $course->getSemester();
    $parsed_semester = $course_manager->parseSemesterMachineName($semester);

    $form->get('formSemesterSeason')->setData($parsed_semester->season);
    $form->get('formSemesterYear')->setData($parsed_semester->yearFull);
});

This works well, but how do I then combine the values back after the form has been submitted? I can do it easily in the controller, but I think I should be able to use form events, and have the data manipulation take place before form validation.

0

1 Answer 1

1

You can combine them back in a POST_SUBMIT listener.

The best way (reuseable) would be to create your own custom form type with a data transformer to split/combine the fields internally.

There are "recipes" in the cookbook but the best way that I found to create it was to rip apart the DateTime field type and associated transformers (DataTransformerChain, DateTimeToArrayTransformer & ArrayToPartsTransformer) for parts and build my own from that.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for pointing out the DateTime field type. This, and the Time field type are perfect examples of what I'm looking to do.

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.