Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony: call form handleRequest but avoid entity persist

Tags:

forms

symfony

I have an entity that models a search form and a form type, I use that form for searching purposes only and I don't want that entity to be modified in database, so, when I do this:

$formModelEntity = $em->getRepository('AppBundle:SearchForm')
                      ->findOneBy(array('name' => 'the_model'));
$formModelForm = $this->createForm(new SearchFormType(), $formModelEntity, array('action' => $this->generateUrl('dosearch'), 'method' => 'POST'));
$formModelForm->handleRequest($request); //or ->submit($request);
if ($formModelForm->isValid())
{
     $formInstanceEntity->setFieldsFromModel($formModelEntity);
     $em->persist($formInstanceEntity);
     $em->flush();
}

The $formModelEntity changes are persisted to database, I want to avoid this but still want to take advantage of handleRequest ability to update the entity with all POST values (for read only purposes).

Is this possible?

like image 716
K. Weber Avatar asked Dec 09 '15 13:12

K. Weber


1 Answers

In symfony, you only have to persist a new entity. If you update an existing entity found by your entity manager and then flush, your entity will be updated in database even if you didn't persist it.

Edit : you can detach an entity from the entity manager before flushing it using this line of code :

$em->detach($formModelEntity);
like image 63
jiboulex Avatar answered Oct 21 '22 07:10

jiboulex