I am using fos_rest in symfony 2.8. I have an Angular client that sends a serialized entity in JSON in order to persist it in the database. It has three related entities.
Ex:
{"auto":
{"usuario":{"id":1},
"modelo":{"id":1},
"color":{"id":1},
"nombre":"Mi Auto",
"kmActual":5300,
"anio":2016}
}
To capture it I have a formType like the following:
class AutoType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('nombre', TextType::class)
->add('kmActual', IntegerType::class)
->add('anio', IntegerType::class)
->add('usuario', UsuarioType::class)
->add('modelo', ModeloType::class)
->add('color', ColorType::class)
->add('id');
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Auto',
'csrf_protection' => false,
'allow_extra_fields' => true,
));
}
I also have three forms: UserType, ModelType and ColorType with structures very similar to AutoType.
In the controller I have the following:
/**
* Collection post action
* @var Request $request
* @return View|array
*/
public function cpostAction(Request $request)
{
$entity = new Auto();
$form = $this->createForm(AutoType::class, $entity);
$form->handleRequest($request);
if ($form->isValid()) {
$entity = $form->getData();
$em = $this->getDoctrine()->getManager();
);
$em->merge($entity);
$em->flush();
return $this->redirectView(
$this->generateUrl(
'get_auto',
array('idAuto' => $entity->getId())
),
Response::HTTP_CREATED
);
}
return $this->view($form->getErrors(), Response::HTTP_BAD_REQUEST);
}
I used merge because when trying to do persist I tried to insert user, model and color as new records. Doing etso inserts in the database but does not update the entity with the id inserted.
What am I doing wrong?