I'm working on an end-of-course project with a group of colleagues on Symfony 7. I created two files messages.en.yaml and messages.fr.yaml in which I created all the language variables, translated them and installed them throughout the backoffice. I'd like to switch from one language to another at the click of a button. But it doesn't work. If I add /{_locale}/ to the paths in my controllers and in the url, I see that my translations work. If I dump and die in my languageController, I also find the values of the locale. But the buttons don't work, there's no automation.
I read the symfony doc, chatted with chatGTP — none of the things I read worked. Nor did my trainers' or colleagues' attempts. I've tried so many things that I can't remember any of them. What I do remember doing is composer require symfony/translation. Then I followed the docs and used chatGTP to come up with a rough rendering of the files I'm attaching.
Here's my translation.yaml:
framework:
default_locale: 'en'
translator:
default_path: '%kernel.project_dir%/translations'
Here's my routes.yaml:
controllers:
resource:
path: ../src/Controller/
namespace: App\Controller
type: attribute
api_login_check:
path: /api/login_check
app.swagger_ui:
path: /api/doc
methods: GET
defaults: { _controller: nelmio_api_doc.controller.swagger_ui }
switch_language:
path: '/{_locale}/'
controller: 'App\Controller\LanguageController::switchLanguage'
requirements:
_locale: 'en|fr'
Here's my language controller:
<?php
namespace App\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class LanguageController extends AbstractController
{
#[Route('/{_locale}/switch-language', name: 'switch_language')]
public function switchLanguage(Request $request, $_locale): Response
{
$request->getSession()->set('_locale', $_locale);
return $this->redirect($request->headers->get('referer'));
}
}
And here are my buttons supposed to switch languages:
<!-- Language Switching Links within the navbar -->
{% if app.request.locale != 'en' %}
<li class="nav-item">
<a class="nav-link" href="{{ path('switch_language', {'_locale': 'en'}) }}">{{ 'English'|trans }}</a>
</li>
{% endif %}
{% if app.request.locale != 'fr' %}
<li class="nav-item">
<a class="nav-link" href="{{ path('switch_language', {'_locale': 'fr'}) }}">{{ 'French'|trans }}</a>
</li>
{% endif %}
I've only been coding for six months, so it's particularly tricky. So I'd be grateful for anyone's help.