DrKey
DrKey

Reputation: 3495

Symfony2 - Get entity in presubmit/submit form event

As the title says, I need to get the entity which is going to be deleted in a form event. I'm using Symfony 2.7. I'm able to get entity on POST_SUBMIT event if it gets created/edited, but I'm not able to get it on PRE_SUBMIT, SUBMIT and also POST_SUBMIT before it gets deleted.

What I tried so far (I wrote results of variables in comments)

public static function getSubscribedEvents()
{
    return array(
        FormEvents::POST_SUBMIT => 'onPostSubmit',
        FormEvents::PRE_SUBMIT => 'onPreSubmit',
        FormEvents::SUBMIT => 'onSubmit'
    );
}

public function onPreSubmit(FormEvent $event)
{
    dump($event->getForm()->getData()); // <-- null
    dump($event->getData()); // <-- array:1 ["submit" => ""]
}

public function onSubmit(FormEvent $event)
{
    dump($event->getForm()->getData()); // <-- null
    dump($event->getData()); // <-- array:0 []
}

public function onPostSubmit(FormEvent $event)
{
    dump($event->getForm()->getData()); // <-- array:0 []
    dump($event->getData()); // <-- array:0 []
}

This is basically how deletion starts. I'll not put the whole functions used by it because I don't think is needed:

public function deleteConfirmAction(Request $request, $id)
{
    $form = $this->createDeleteForm($id);
    $form->handleRequest($request);
    $entity = $coreService->getArea($id);
    if ($form->isValid()) {
        $coreService->deleteEntity($entity); // will remove also relationships
        $coreService->persistChanges(); // basically a Doctrine flush()
        $this->addFlash('success', GlobalHelper::get()->getCore()->translate('flash.entity.delete.success'));
        return $this->redirect($this->generateUrl('index')));
    }
}

private function createDeleteForm($id)
{
    return $this->createFormBuilder()
        ->setAction($this->generateUrl('area_delete_confirm', array('id' => $id)))
        ->setMethod('POST')
        ->add('submit', 'submit', array('label' => 'entity.delete', 'attr' => ['class' => 'btn button-primary-right']))
        ->getForm();
}

Any idea?

Upvotes: 0

Views: 948

Answers (1)

gintko
gintko

Reputation: 697

You don't pass your entity to the form, you can do this by specifying first argument for createFormBuilder call:

$this->createFormBuilder(['entity' => $entity]);

and then you should be able to retrieve entity in pre submit event listener.

Upvotes: 1

Related Questions