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.
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.