Reputation: 2773
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?
Upvotes: 6
Views: 3017
Reputation: 3031
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);
Upvotes: 6
Reputation: 803
the method handleRequest Does not save the changes. it only updates the object within your method.
public function newAction(Request $request)
{
// just setup a fresh $task object (remove the dummy data)
$task = new Task();
$form = $this->createFormBuilder($task)
->add('task', TextType::class)
->add('dueDate', DateType::class)
->add('save', SubmitType::class, array('label' => 'Create Task'))
->getForm();
$form->handleRequest($request);
if ($form->isValid()) {
// ... perform some action, such as saving the task to the database
return $this->redirectToRoute('task_success');
}
return $this->render('default/new.html.twig', array(
'form' => $form->createView(),
));
}
the following snippet exists at http://symfony.com/doc/current/book/forms.html
and as you can see the entity is not persisted.
You're are probably adding a persist/flush and that's what's causing the entities to be updated.
Upvotes: 4