2017-09-27 97 views
0

我有一个注册模式窗口,我想在成功注册后重定向用户在同一页面上。Symfony 3 - FosUserBundle - 注册后重定向到当前页面

为此,我用包含Request对象的新关联控制器覆盖fos_user_registration_confirmed路由。

在我的表单操作字段中,我尝试添加一个包含当前路径的参数current_path,然后用$current_path = $request->attributes->get('current_path');检索它,但它始终为NULL。

我用一个表单隐藏参数尝试同样的事情,并用$current_path = $request->request->get('current_path');检索它,但它总是为NULL。

表单中的当前路径是正确的,但似乎我无法在控制器中检索它。

public function registrationConfirmedAction(Request $request) 
{ 
    // POST: doesn't work 
    $current_path = $request->request->get('current_path'); 

    // GET: doesn't work 
    if($current_path == NULL) 
     $current_path = $request->attributes->get('current_path'); 

    if($current_path != NULL) 
     return new RedirectResponse($current_path); 

    return new RedirectResponse($this->generateUrl('pp_home_homepage')); 
} 

编辑:我如何获得当前路径

的current_path的是我register_content.html.twig模板:

{% set current_path = app.request.get('current_path') %} 

我将其添加在代码中的两个地方:

{{ form_start(form, { 
    'method': 'post', 
    'action': path('fos_user_registration_register') ~ '?current_path=' ~ current_path, 
    'attr': { 
     'class': 'fos_user_registration_register', 
     'novalidate': 'novalidate', 
    } 
}) }} 

此处:

<input type="hidden" name="current_path" value="{{ current_path }}"> 

的属性在我的基座模板生成:

{% set current_path = path(app.request.attributes.get('_route'), app.request.attributes.get('_route_params')) %} 

然后我将其发送给我的控制器:

{{ render(controller(
    'PPUserBundle:Registration:register', 
    {'current_path': current_path} 
)) }} 
+0

你可以显示代码在哪里添加当前网址 – Chibuzo

+0

@Chibuzo编辑。但是,正如我之前所说的,'current_path'值是有效的,它没有问题。 – Arphel

回答

0
我固定,在`regiserAction`方法。我在检测表单提交之前检索当前路径: $ current_path = $ request-> request-> get('current_path'); 然后,我在`if($ form-> isValid())`块中将`return $ response;`更改为: 返回新的RedirectResponse($ current_path);


编辑:使用监听

我发现,这是更好地创建实施EventSubscriberInterface监听器:

public static function getSubscribedEvents() 
{ 
    return array(
     FOSUserEvents::REGISTRATION_SUCCESS => 'onRegistrationSuccess' 
    ); 
} 

public function onRegistrationSuccess(FormEvent $event) 
{ 
    $current_path = $event->getRequest()->request->get('current_path'); 
    $response = new RedirectResponse($current_path . '?registration_confirmed=true'); 
    $event->setResponse($response); 
} 

然后不要忘记修改app/config/services.yml

pp_user.registration_success: 
    class: PP\UserBundle\EventListener\RegistrationSuccess 
    autowire: true 
    tags: 
     - { name: kernel.event_subscriber } 
相关问题