Ajax form submission in symfony2 with graceful degradation for users without javascript

后端 未结 3 1358
悲&欢浪女
悲&欢浪女 2021-01-30 04:57

I am building a web application that involves forms. The framework being used is symfony2. I would like to have everything working for users without javascript, and then progres

3条回答
  •  一生所求
    2021-01-30 05:24

    Another option is to have your controller return something other than a response and use the kernel.view event to transform that into what you want. This would be better DRY because the logic is encapsulated in the listener. You just need to decide what you want your controllers to return.

    if ($form->isValid()) {
        return new Something($redirectUrl, $ajaxData);
    }
    

    And in your listener:

    public function onKernelView($event)
    {
        $request = $event->getRequest();
        $result = $event->getControllerResult();
    
        if ($result instanceof Something) {
            if ($request->isXmlHttpRequest()) {
                $event->setResponse(new Response(json_encode($result->getAjaxData())));
            } else {
                $event->setResponse(new RedirectResponse($result->getRedirectUrl()));
            }
        }
    }
    

提交回复
热议问题