Symfony2: Is the Referrer object similar to the Request object?

I try not to find the "referrer" object for use in my controller. I expected that there would be an object similar to a query object with parameters defining _controller, _route and Arguments.

What I'm trying to do is a language switch that redirects the user to the same page in the new language . Something along the line:

public function switchLangAction($_locale)
{
    $args = array();
    $newLang = ($_locale == 'en') ? 'fr' : 'en';

    // this is how I would have hoped to get a reference to the referrer request.
    $referrer = $this->get('referrer');
    $referrerRoute = $referrer->parameters->get('_route');
    $args = $referrer->parameters->get('args'); // not sure how to get the route args out of the params either!
    $args['_locale'] = $newLang;

    $response = new RedirectResponse( $this->generateUrl(
        $referrerRoute,
        $args
    ));

    return $response;
}

It is also possible that there is another way to do this - I know the rails, for example, there is a redirect_to: back method.

Any help would be greatly appreciated.

+5
source share
2 answers

?

my_login_route:
    pattern: /lang/{_locale}
    defaults: { _controller: AcmeDemoBundle:Locale:changeLang }
    requirements:
        _locale: ^en|fr$

namespace Acme\DemoBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class LocaleController extends Controller
{
    public function switchLangAction($_locale, Request $request)
    {
        $session = $request->getSession();
        $session->setLocale($_locale);
        // ... some other possible actions

        return $this->redirect($session->get('referrer'));
    }
}

,

$session->set('referrer', $request->getRequestUri());

, .

+4

LocaleController {

public function indexAction()
{
    if(null === $this->getRequest()->getLocale()){
        $locale = $this->getRequest()->getPreferredLanguage($this->getLocales());
        $this->getRequest()->setLocale($locale);
    }
    else{
        $locale = $this->getRequest()->getLocale();
    }

    return $this->redirect($this->generateUrl('corebundle_main_index', array('_locale' => $locale)));
}

public function changeLocaleAction($_locale)
{
    $request = $this->getRequest();
    $referer = $request->headers->get('referer');
    $locales = implode('|',$this->getLocales());
    $url = preg_replace('/\/('.$locales.')\//', '/'.$_locale.'/', $referer, 1);
    return $this->redirect($url);
}

private function getLocales()
{
    return array('ru', 'uk', 'en');
}


/**
 * @Template()
 */
public function changeLocaleTemplateAction()
{
    return array();
}

}

0

All Articles