Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embed form controller in twig template: can't redirect in embedded controller after submit

Tags:

php

symfony

I have index action, that print 1) form for creating new Entity; 2) list of all Entities:

public function indexAction()
{
    $em = $this->getDoctrine()->getEntityManager();

    $entities = $em->getRepository('MyBundle:Entity')->findAll();

    return array(
        'entities' => $entities,
    );
}

Twig:

{% block content %}
    {% render "MyBundle:Entity:new" %}
    {% render "MyBundle:Entity:list" %}
{% endblock %}

newAction in Entity Controller is standart form controller:

public function newAction()
{
    $entity = new Entity();
    $form = $this->createForm(new EntityType(), $entity);

    $request = $this->getRequest();
    if ($request->getMethod() == 'POST') {
        $form->bindRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getEntityManager();
            $em->persist($entity);
            $em->flush();

            // NOT WORK
            return $this->redirect($this->generateUrl('entity_show',
                array('id' => $entity->getId())));
        }
    }
    return array(
        'form' => $form->createView(),
    );
}

Redirect after entity persisting isn't work, error:

An exception has been thrown during the rendering of a template
("Error when rendering "http://example.com/app_dev.php/url/"
(Status code is 302).") in MyBundle:Default:index.html.twig at line 2.
like image 803
alexfv Avatar asked Jan 26 '12 11:01

alexfv


1 Answers

Unfortunately, this is by design. You cannot redirect from embedded controllers. As a workaround, you can post to different URL, save referrer, do stuff you need in there and redirect back with results.

like image 69
Ondrej Slinták Avatar answered Nov 05 '22 19:11

Ondrej Slinták