简体   繁体   中英

Symfony: call form handleRequest but avoid entity persist

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?

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.

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

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