I am trying to change page language by a dropdown. Dropdown is generated by this code {{ form_widget(registrationForm.locale, { 'attr': {'onChange': 'languageChange()'} }) }}
in the twig.
Ajax function
function languageChange() {
let selectedLanguage = $('#email_form_locale').val();
$.ajax({
url: '{{ path('change_locale') }}',
type: 'POST',
dataType: 'json',
data: {'selectedLanguage': selectedLanguage},
async: true,
success: function(data, status) {
console.info(data);
location.reload();
},
error : function(xhr, textStatus, errorThrown) {
alert('Ajax request failed.');
}
});
}
Controller function
/**
* @Route("/registration/changeLocale", name="change_locale")
* Method({"GET","POST"})
*/
public function changeLocale (Request $request)
{
$user = new User();
$form = $this->createForm(EmailFormType::class, $user);
if ($request->isXmlHttpRequest()) {
$jsonData = array();
$temp = $request->request->all();
$jsonData[0] = $temp;
$request->getSession()->set('_locale', $temp['selectedLanguage']);
$request->setLocale($temp['selectedLanguage']);
$jsonData[1] = $request->getLocale();
$user->setLocale($temp['selectedLanguage']);
return new JsonResponse(array(
'jsonData' => $jsonData,
'html' => $this->renderView('main/registration.html.twig', array('registrationForm' => $form->createView()))
)
);
} else {
return $this->render('main/registration.html.twig');
}
I am trying to render the view after Jason response. Then the page must be selected languge( I have added the translation module and words for certain languages in translation folder and If I change the locale in services.yaml languages are changing) Please help me to do this.