I am working with Symfony 2.7 and have created a custom FormType based on Symfonys EntityType
. Within the FormEvents::POST_SUBMIT of this type I update the received data by adding a special entity. However this chance is not send back to the controller:
Action within controller:
public function customEditAction(Request $request) {
$formData = $this->getFormData();
// formData has a property myEntities which is array of MyEntity
$form = $this->createForm('my_form_type', $formData);
$form->handleRequest($request);
if ($form->isValid()) {
foreach ($formData->getMyEntities() as $myEntity)
dump($myEntity);
}
...
}
my_form_type
class MyFormType extends AbstractType {
...
public function getName() {
return 'my_form_type';
}
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('myEntities', 'my_entities_type', array(
...
),
));
...
}
}
my_entities_type
class MyEntitiesType extends AbstractType {
...
public function getParent() {
return 'entity';
}
public function getName() {
return 'my_entities_type';
}
public function buildView(FormView $view, FormInterface $form, array $options) {
...
}
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) use ($options) {
// Update data with a special entity.
$data = $event->getData();
$specialEntity = $this->getSomeSpecialEntity();
$data[] = $specialEntity;
// Dump shows, that the entiy was correctly added to $data
foreach ($data as $myEntity)
dump($myEntity);
$event->setData($data);
}
...
}
}
Expected Result:
- Form is created with some set of entities within
$formData->getMyEntities()
- Form is presented to the user.
EntityType
(parent ofMyEntitiesType
) fetched all available Entities to build a selection. Entities within$formData->getMyEntities()
are pre-selected - User makes his choice and selects a new set of Entities, e.g.
Entity1
andEntity2
- Form is submitted
- In
FormEvents::POST_SUBMIT
$specialEntity
is added to the data/selection - Both dumps (within
POST_SUBMIT
and within the controller) should show the selected entities including $specialEntity
Everything works fine beside step 6: While the dump within POST_SUBMIT
shows that $specialEntity
is in $data, the dump within the controller only shows the user selected entities...
Why isn't the changed data submitted back to the controller? What do I have to do, to get the updated data to the controller?
EDIT:
Adding the special entity in FormEvents::SUBMIT
does not work, since this entity is not managed and will thus result in an exception within the EntityType
implementation.