Reputation: 1840
If I have a FormType Object with setDefaultOptions method that sets a data_class, how should I get the entity from it for persisting in Doctrine ORM?
$form = $this->createForm(new CarModelsType());
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist(????HERE????);
}
Should I put $form->getData() in "????HERE????". I'm just not sure if it's the correct way since it looks nasty
Upvotes: 0
Views: 1408
Reputation: 8645
There are 2 cases.
1) You gave an object to your form :
The object is automatically updated and hydrated with new values from the form, you can save the object.
$carModel = ... ; // Get or new object of the entity
$form = $this->createForm(new CarModelsType(), $carModel); // Note, $carModel is given
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($carModel); // Save the object $carModel
$em->flush();
}
2) You don't give an object when intitializing your form :
So you need to retrieve the entity with $form->getData()
.
$form = $this->createForm(new CarModelsType()); // Note : no object given
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($form->getData()); // You get the object after with $form->getData()
$em->flush();
}
In addition :
Note that $form->getData()
works always, even when you give an object to your form ! So, you can use $form->getData()
all the time !
Upvotes: 0
Reputation: 1272
For a createAction():
public function createAction(Request $request)
{
$entity = new CarModel();
$form = $this->createForm(new CarModelTypeType(), $entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
//...
}
//...
}
Upvotes: 1