Render controller and get form errors from child

别等时光非礼了梦想. 提交于 2019-12-13 02:26:50

问题


I have a template where I render a widget which contains a form:

{{ render(controller('ApplicationDemoBundle:Demo:newWidget', {'demo' : entity })) }}

The newWidgetAction calls a createAction:

public function createAction(Request $request)
{
    $entity = new Demo();
    $form = $this->createCreateForm($entity);
    $form->handleRequest($request);

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

        return $this->redirect($this->generateUrl('demo_show', array('id' => $entity->getId())));

    }

    return array(
        'entity' => $entity,
        'form'   => $form->createView(),
    )
    // Something like this would be awesome with passing the form containing errors with
    // return $this->redirect($this->getRequest()->headers->get('referer'));
}

Imagine the submitted form (user acts in show theme) produces an error. This would make a return to the newWidget template which does not display the full layout.

My question is now: What is the right way to pass the errors from the child controller (newWidget) to the main template (show)?, without modifying the showActions function parameter to pass the formerrors over there.

There is a similar thread to this question: Symfony2 render and form In this case where sessions used but I'm more than curious if this is the way to go.


回答1:


The problem is that each fragment (a sub-controller) uses a virtual request. This is to protect the original request from modification by possibly unexpected forwards, and a fragment is essentially a forward taking place during a rendering stage.

It is possible to access the top level request using: $this->container->get('request'); then handing the request with the form in the fragment, but this may get very confusing very quickly if you are using multiple forms per page.

My strategy is to follow a convention that limits the number of validated form on a page to just one. Any other forms don't require validation, or it is otherwise impossible for a form to be submitted incorrectly (hacked forms would throw server side exceptions, but the user should only see those if they are being naughty).

Try to structure your template inheritance to accommodate navigation to forms, while always showing most of the same layouts and data. You can do this by expanding the use of fragments which gives the bonus of separating your display logic.



来源:https://stackoverflow.com/questions/19896639/render-controller-and-get-form-errors-from-child

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!