My local works everywhere on my website but I cant tell the application the set the proper local on the root of the application.
For exemple :
If my website is http://mycompany.com I want that, when I enter this address the application guess what is my local and set it at the end of the url
http://mycompany.com/en if the local exist on my application. Here en or fr and if not the default en
For now when i go to home page I always get english version but my browser is set in french
routing.yml :
_welcome:
pattern: /{_locale}
defaults: { _controller: MyBundle:Default:landing, _locale: en }
requirements:
_locale: en|fr
See this question asked a few days ago and take a look at the first method in the language listener. It does exactly what you need. And take care of the right settings in config.yml
With the help of many other questions related to locale and symfony2 I finally get want I want ! I guess it is not the perfect answer but at least it works !
My landing action is defined in my routing as _welcome route. It is this action that is loaded when I go to the url's root.
/**
* #Route("/landing")
* #Template()
*/
public function landingAction() {
$localeAvailable = array('en', 'fr');
//user language
$localeUser = substr($this->getRequest()->getPreferredLanguage(), 0, 2);
//application language
$localeApp = $this->getRequest()->attributes->get('_locale');
//Redirect to the good locale page
//only if the locale user is on our manager locale and it is not the current locale of the application
if(in_array($localeUser, $localeAvailable) && $localeApp!=$localeUser){
return $this->redirect($this->generateUrl("_welcome", array('_locale' => $localeUser)));
}
return array();
}
Related
I have a need to set the locale based on subdomain , using Sylius based on Symfony.
I have done the below to make it work, but we need the Locale Code in subdomain mapped to a localcode ( "jp.portal.com" => Locale "ja")
#Routing YML
portal:
resource : "../../src/proj/Resources/config/routing.yml"
host: "{_locale}.%site_host%"
prefix: /
requirements:
_locale: 'en|jp'
defaults:
_locale: 'en'
Difficulty i have is mapped a non locale code like 'jp' to 'ja'
I have tried with below locale Listiner , but it does not help
I get errors
if (strpos($host, 'jp') !== false) {
$locale = 'ja';
} else {
$locale = 'en';
}
$request->setLocale($locale);
if (null !== $this->router) {
$this->router->getContext()->setParameter('_locale', $request->getLocale());
}
I get errors in generate url path througth the site
An exception has been thrown during the rendering of a template
("Parameter "_locale" for route "sylius_shop_homepage" must match "jp"
("en" given) to generate a corresponding URL.").
How can I define my Symfony2 routes to show a different homepage for authenticated users and non-authenticated users? For example, I want to do something like this in my routing.yml file:
homepage_authenticated:
path: /
defaults:
_controller: AcmeBundle:Home:homeAuthenticated
requirements:
user: is_authenticated_remembered # <--- this part here
homepage:
path: /
defaults:
_controller: AcmeBundle:Home:home
Now obviously this doesn't work because I just invented it, but I'm sure there must be a way to do this, but I can't find it. I have an idea Expressions may be the solution to this somehow, but I can't find any examples of actually using them, anywhere.
As Malcom suggested in the comment, it is better to handle redirects/page-rendering based on user's authentication status in the controller.
The security context saves the role related data and the authentication status. You can redirect your users to different pages by checking
$this->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY') and $this->get('security.context')->isGranted('ROLE_NAME').
For example:
public function homeAction()
{
$em = $this->getDoctrine()->getEntityManager();
if ($this->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY')) {
//Path handling for authenticated users
if ($this->get('security.context')->isGranted('ROLE_ADMIN')) {
return $this->redirect($this->generateUrl('admin_homepage'));
}
if ($this->get('security.context')->isGranted('ROLE_USER')) {
return $this->render('VenomCoreBundle:Default:home.html.twig', array(
'notifications' => $notifications,
'unApprovedCount' => $unApprovedCount,
'status' => $stats,
));
}
}
//non authenticated users are redirected here
return $this->render('VenomCoreBundle:Default:login.html.twig');
}
I'm having a strange issue with Symfony2.2. I have a project using two languages : en/fr. So I create as usual (like Symfony2.0) two translation files "messages.en.yml" and "messages.fr.yml" in Ressources/Views/translations/. But Translations in twig could not change even if we set the request object and the locale session. Translation is always set by the default_locale (config.php).
Example : if default_locale = en, all my website (in twig) is translated in en, even if i set the _locale object in fr (request and session). Of course if I manually change the default_locale to fr the website is naturally in fr...
However, _locale session works but I don't know if locale request works, and of course translation works in controllers too...
There is my files :
config.yml:
framework:
#esi: ~
translator: { fallback: %locale% } # = en
# ...
default_locale: %locale% # = en
Controller :
public function indexAction()
{
$this->get('session')->set('_locale', 'fr');
$this->getRequest()->setLocale($lang);
exit($this->getRequest()->getLocale()); // = fr
exit($this->get('translator')->trans('Symfony2 is great')); // = Symfony2 est génial
return $this->render('TestBundle:Controller:test.html.twig');
View :
{% block content %}
<p>lang : {{ app.request.locale }}</p> {#} = "fr", OK{#}
<p>{{ 'Symfony2 is great'|trans }}</p> {#} = "Symfony2 is great", WAIT WHAT?{#}
I must resign myself to force the locale at the beginning of the method controller to have the requested locale (stored in session) like that :
Controller:
if($this->get('session')->get('_locale')){
$lang = $this->get('session')->get('_locale');
$this->getRequest()->setLocale($lang);
}
In other words, I do have a problem with the registration of the request object... Because the last code works well in the controller, and shows well the locale in twig page with app.request.locale, but not the translations... (sorry for my bad english and thanks for helping)
I had the same issue due to the low priority of my event listener. The locale would be overridden by the Translator's TranslatorListener. Increasing the priority of my event listener did the trick for me:
services:
app.locale_listener:
class: AppBundle\EventListener\LocaleListener
tags:
- { name: kernel.event_listener, priority: 11, ... }
Source: https://github.com/symfony/symfony/issues/12878#issuecomment-68628808
Parameter _locale in routing holds your locale value.
Look here on this page
Symfony - Book - Translation - Local and the URL
From Symfony 2.1 they have this kind of logic:
Since you can store the locale of the user in the session, it may be tempting to use the same URL to display a resource in many different languages based on the user's locale. For example, http://www.example.com/contact could show content in English for one user and French for another user. Unfortunately, this violates a fundamental rule of the Web: that a particular URL returns the same resource regardless of the user. To further muddy the problem, which version of the content would be indexed by search engines?
A better policy is to include the locale in the URL. This is fully-supported by the routing system using the special _locale parameter:
Now when you want to sel local, this doesn't work any more
$this->get('session')->set('_locale', 'fr');
You can use request insted of session now but you can not have session-logic with _local from Symfony 2.0 unless you simulate it with event listener on kernel request.
When dealing with the Sylius e-commerce bundles I have found what seems to be a way of configurig the template for a route, that I didn't know:
I have tested in a fresh Symfony RC 2.2.0 with vendors installation.
This would be in the routing.yml
_welcome:
pattern: /
defaults:
_controller: AcmeDemoBundle:Welcome:index
_template: AcmeDemoBundle:Welcome:index # added by me
this generates an error:
FatalErrorException: Error: Call to a member function getTemplate() on
a non-object in
.... \vendor\sensio\framework-extra-bundle\Sensio\Bundle\FrameworkExtraBundle\EventListener\TemplateListener.php
line 62
now, in TemplateListener, what we have is:
if (!$configuration = $request->attributes->get('_template')) {
return;
}
if (!$configuration->getTemplate()) {
$guesser = $this->container->get('sensio_framework_extra.view.guesser');
$configuration->setTemplate($guesser->guessTemplateName($controller, $request, $configuration->getEngine()));
}
$configuration is a String, actually the template I put in routing.yml (AcmeDemoBundle:Welcome:index). Checked by adding a var_dump and also inspecting ParameterBag -> get method which is what $request->attributes is.
So. Why TemplateListener is expecting an object? What am I missing? Am I missconfiguring in routing.yml?
This parameter is not available in Symfony itself.
Feature is provided by SyliusResourceBundle and available only in Sylius controllers.
And apparently _template request attribute conflicts with SensioFrameworkExtraBundle, which uses same name to store object.
We have to move those parameters one config node deeper, to avoid such problems in future.
You can keep an eye on the https://github.com/Sylius/SyliusResourceBundle repository, fix should arrive today.
When I try to use 2 optional variables in Symfony2 routing I have th error: No route found for "GET /"
In routing.yml I have:
AcmeAshavatBundle_homepage:
pattern: /{page}/{ads_on_page}/
defaults: { _controller: AcmeAshavatBundle:Page:index, page:1, ads_on_page:2 }
requirements:
_method: GET|POST
And when i go to http://localhost:8080/AshavatSy/web/app_dev.php/ I have the error. The intresting is that if I run http://localhost:8080/AshavatSy/web/app_dev.php/1 it works well.Also, if I change the path to pattern: /main/{page}/{ads_on_page}/ it works well.
What is the problem?
I'd like to ask, that someone will try to do like this [e.g. pattern: /a/b/ defaults: {... a:1,b:2}, or as he thinks you should do it] in his project, and see is it a common problem...
I managed to have something similar working by defining two routes, pointing to the same controller, using default parameters. In my case, using annotations:
/**
* #Route("/products/{catId}/{prodId}", defaults={"catId"="", "prodId"=""})
* #Route("/products/")
* #Template()
*/
public function indexAction($catId = null, $prodId = null) {
...
I think that using default parameters only, Symfony would expect two /.
HTH
I think you forgot to pass these two arguments to your IndexAction() in controller.
Try this code
Public function indexAction($page,$ads_on_page)
{}
Hope this helps you.