简体   繁体   中英

Getting entity from form with data_class - the correct way in Symfony2

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

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();

        //...
    }
    //...
 }

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 !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM