I have a Field class and a FieldType class associated to it and I want to create a interface where the user can edit the FieldType of all the Fields at once.
So I did the following:
protected function createUpdateForm() {
$fieldList = $this->getDoctrine()->getRepository('AppBundle:Field')->findAll();
$fieldTypeList = $this->getDoctrine()->getRepository('AppBundle:FieldType')->findAll();
$form = $this->createFormBuilder();
foreach ($fieldList as $field){
$form->add($field->getDescription(), ChoiceType::class,
['choices' => $fieldTypeList,
'choice_label' => 'getDescription',
'multiple'=>false, 'expanded'=>true,
'data' => $field->getFieldType()]);
}
$form->add('action', SubmitType::class, ['label' => 'Update']);
$form->add('cancel', SubmitType::class, ['label' => 'Cancel']);
return $form->getForm();
}
It takes all the Fields from the database and creates a Radio group with the FieldTypes as the image shows (just the end of the form):
So for each Field the user can select the type and update the values. This is how I am updating the form, and that is what I do not like:
foreach ($form->getData() as $fieldType){
$field = array_shift($fieldList);
$field->setFieldType($fieldType);
$em = $this->getDoctrine()->getManager();
$em->flush();
}
It works, but everything look like a bodge, I do not like this. I'm starting with Symfony so I'm not sure, but there should be a better way to create the kind of form I need and persist it. I was trying to create a ColletionType, but it is not working out.
Does anybody know a better way to do this?
I have a more complex case that will use a similar logic so I'm trying to figure this out.
