ximo12 ximo12 - 3 years ago 332
Twig Question

Refresh page in controller symfony 3

I have this function in controller:

/**
* @Route("/{lang}", name="homepage_lang")
* @param Request $request
* @param $lang
* @return \Symfony\Component\HttpFoundation\Response
*/
public function indexLangAction(Request $request, $lang)
{

if (isset($lang)){
$newLang = $lang;
}else{
$localeLang = $request->getLocale();
$newLang = $localeLang;
}

$this->get('session')->set("_locale", $newLang);

// replace this example code with whatever you need
return $this->render('default/index.html.twig', [
'base_dir' => realpath($this->getParameter('kernel.project_dir')).DIRECTORY_SEPARATOR,
]);
}


And Buttons in twig like this:

<button onclick="window.location.href='/es'" type="button">EspaƱol</button>


When I click the page refresh but not change the language, I have to click two times to change the language.

Answer Source

If you're changing the session in the controller, you'll need to reload after doing so. Try something like this:

/**
 * @Route("/{lang}", name="homepage_lang")
 * @param Request $request
 * @param $lang
 * @return \Symfony\Component\HttpFoundation\Response
 */
public function indexLangAction(Request $request, $lang)
{
    $session = $this->get('session');
    if ($session->has("_locale") && $lang !== $session->get("_locale")) {
        $session->set("_locale", $lang);
        return new RedirectResponse('/' . $lang);
    }

    return $this->render('default/index.html.twig', [
        'base_dir' => realpath($this->getParameter('kernel.project_dir')).DIRECTORY_SEPARATOR,
    ]);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download