I'm using Fos_rest to do a webservice. I recive an entity from an Angular App in JSON. JSON example :
{"model":
{
"trademark":
{"id":1,"name":"Alfa Romeo"},
"type":
{"id":1,"code":"car","name":"Car"},
"name":"147"
}
}
The entity is composed of two sub entities, called "trademark" and "type".
When receiving a POST, in controller does the following:
public function cpostAction(Request $request, $idTrademark)
{
$entity = new Model();
$form = $this->createForm(ModeloType::class, $entity);
$form->handleRequest($request);
if ($form->isValid()) {
$entity = $form->getData();
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
/*do things with the entity and return*/
}
}
The problem is given when doing Flush, since it recognizes "trademark" and "type" as new entities, since these already exist when owning an "id". How can I force the entity manager to recognize the entities "trademark" and "type" from the database?
P.S: Form Type:
class ModelType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('name')
->add('trademark', TrademarkType::class)
->add('type', TypeType::class)
->add('id');
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Model',
'csrf_protection' => false,
'allow_extra_fields' => true,
));
}
}
You should not do a
find()
: it does a database request. Prefer:It does not a database query. The only problem is
getReference
does not check if the entity is still existing in the database. For megetReference
should only be used to transform an id to the doctrine proxy object