Set locale in Symfony 2.1 - php

I am trying to have a language switcher on my symfony 2.1 website.
I followed the official documentation, set the translation files but setting the locale with $request->setLocale('en_US'); doesn't seem to work. After some research, I found this question which provides a beginning of an answer with this listener technique.
However, I still don't manage to have it working, I'm not so sure about my listener declaration, is something wrong with it?
My controller:
public function englishAction(Request $request)
{
$this->get('session')->set('_locale', 'en_US');
return $this->redirect($request->headers->get('referer'));
}
Service declaration in config.yml:
services:
my_listener:
class: "FK\MyWebsiteBundle\Listener\LocaleListener"
My routing:
homepage:
pattern: /{_locale}
defaults: { _controller: FKMyWebsiteBundle:Default:index, _locale: en }
requirements:
_locale: en|fr|cn
about:
pattern: /{_locale}/about
defaults: { _controller: FKMyWebsiteBundle:Default:about, _locale: en }
requirements:
_locale: en|fr|cn

The declaration of the LocaleListener in yml (inspired by the current declaration of the new LocaleListener: \vendor\symfony\symfony\src\Symfony\Bundle\FrameworkBundle\Resources\config\web.xml)
services:
my_listener:
class: "FK\MyWebsiteBundle\Listener\LocaleListener"
arguments: [%locale%]
tags:
- { name: kernel.event_subscriber }
Some snippets:
A language switcher in your template:
{% for locale in ['en', 'fr', 'cn'] %}
<li {% if locale == app.request.locale %}class="active"{% endif %}>
{{ locale }}
</li>
{% endfor %}
A redirection with locale change from a controller:
$LocalizedUrl = $this->get('router')->generate(
$request->attributes->get('_route'),
['_locale' => $locale] + $request->attributes->get('_route_params')
);
return new \Symfony\Component\HttpFoundation\RedirectResponse($LocalizedUrl);

You should get the translator instance linked to your symfony kernel container:
$this->container->get('translator')->setLocale('fr');

Related

An exception has been thrown during the rendering of a template ("Controller not found:

After updating from Symfony 3.4 to 4.0 and verifying the operation, the following error occurred.
Do you have any idea?
I added the tride code to routes.yaml by referring to the post below, but it didn't change.
Override a controller Symfony 3.4/4.0
Error
An exception has been thrown during the rendering of a template
("Controller not found: service "#AhiSpAdminBundle/Hq/Image/manager" does not exist.").
Resources/views/Hq/Staff/input.html.twig
{# Image management dialog #}
<div id="imageDialog" title="Image management">
{{ render(controller("#AhiSpAdminBundle/Hq/Image/manager", {"modal": true})) }}
</div>
routes.yaml
ahi_sp_admin:
resource: "../src/Ahi/Sp/AdminBundle/Controller/"
type: annotation
prefix: /admin/
schemes: "%secure_scheme%"
#Tried code
ahi_sp_admin_hq_image_manager:
path: /admin/hq/image/manager/
defaults: { _controller: "#AhiSpAdminBundle/Hq/Image/manager" }
ImageController.php
/**
* Image management panel
*
* #Method("GET")
* #Route("/manager")
*
* #Template("#AhiSpAdminBundle/Hq/Image/manager.html.twig")
*/
public function managerAction(Request $request)
{
$routeParams = $request->get('_route_params');
$uploadUrl = $this->generateUrl("ahi_sp_admin_hq_image_save");
return array(
'modal' => isset($routeParams["modal"]) ? $routeParams["modal"] : false,
'form' => $this->createUploadForm($uploadUrl)->createView(),
);
}
That's not how you render a controller.
{{ render(controller(
'App\\Controller\\ArticleController::recentArticles',
{ 'max': 3 }
)) }}
It's clear from the doc
To include the controller, you’ll need to refer to it using the standard string syntax for controllers (i.e. controllerNamespace::action):
https://symfony.com/doc/4.0/templating/embedding_controllers.html

SensioFrameworkExtraBundle

I'm using Symfony 3.3 and i'm trying to use FOSRestController to make an API.
Here is my config files :
# SensioFrameworkExtra Configuration
sensio_framework_extra:
view: { annotations: false }
# FOSRest Configuration
fos_rest:
format_listener:
rules:
- { path: '^/api', priorities: ['json'], fallback_format: 'json' }
- { path: '^/', stop: true }
view:
view_response_listener: true
Controller :
<?php
namespace AppBundle\Api;
use FOS\RestBundle\Controller\Annotations as REST;
use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\View\View;
class MyController extends FOSRestController
{
/**
* #REST\Get("/some-url")
* #REST\View()
*
* #return View
*/
public function getSomethingAction()
{
$view = View::create();
return $view;
}
}
The issue is about the view_response_listener, i'm having this error message :
(1/1) RuntimeException
You must enable the SensioFrameworkExtraBundle view annotations to use the ViewResponseListener.
Routing :
api_something:
type: rest
resource: AppBundle\Api\MyController
The bundle is already installed and added to the AppKernel.php file
Can something help me with this ?
Thanks
Remove your configuration of sensio_framework_extra :
sensio_framework_extra:
view: { annotations: false }
Because the default configuration is annotations: true (you can look at vendor/sensio/framework-extra-bundle/DependencyInjection/Configuration.php)
Let the default configuration of sensio_framework_extra https://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/index.html#configuration
You may have forgotten to activate the annotations of serializer in config.yml (https://symfony.com/doc/current/serializer.html#using-serialization-groups-annotations)
I suggest you to try this configs :
#app/config/config.yml
framework:
....
serializer: { enable_annotations: true }
fos_rest:
....
view:
view_response_listener: 'force'
Documentation of FosRestBundle view_response_listener :
http://symfony.com/doc/master/bundles/FOSRestBundle/3-listener-support.html
http://symfony.com/doc/master/bundles/FOSRestBundle/view_response_listener.html
Try to create the directory AppBundle/Api/Controller. And put your MyController.php into it. Your controller will be named
\AppBundle\Api\Controller\MyController
Copy the following code to your main services.yml
sensio_framework_extra.view.listener:
alias: Sensio\Bundle\FrameworkExtraBundle\EventListener\TemplateListener
Source of the solution:
https://github.com/FriendsOfSymfony/FOSRestBundle/issues/1768#issuecomment-340294485
another solution from mentioned source:
in bundles.php the Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle must be located after FOS\RestBundle\FOSRestBundle to work properly
Answer for the same question with Symfony 4.0
routes/rest.yaml Routing configuration
app_admin_users:
type: rest
resource: App\Controller\Api\Admin\User\UsersController
prefix: /api
fos_rest.yaml view response listener enabled
fos_rest:
view:
view_response_listener: true
framework_extra.yaml view annotations enabled
sensio_framework_extra:
view: { annotations: true }
config.yaml imports fos_rest and framework_extra
imports:
- { resource: fos_rest.yaml }
- { resource: framework.yaml }
- { resource: framework_extra.yaml }

Symfony 3 set Translation from own dictionary, and switch with url

I creating new easy web with Symfony 3 (I am new with Symfony, I check some post in google, doc in Symfony or here on StackOverflow but nothing does not work) and I need set only:
url routing / as default en lang and /cs for czech lang, /fr for french lang, with universal option to switch another page for example /contacts, /fr/contacts /fr/about etc
use my own translation yml file located in app/Resources/translations
use localization in twig like this {{ 'someone'|trans }}
I set config.yml:
parameters:
locale: cs
framework:
translator: { fallbacks: [cs] }
messages.en.yml
contacts: Contacts
and call it in base.html.twig:
{{ contacts|trans }}
Thanks a lot
This is my working solution
config.yml:
parameters:
locale: cs
app_locales: cs|en
web_root: '%kernel.root_dir%/../web/'
framework:
#esi: ~
translator: { fallbacks: ['%locale%'] }
default_locale: "%locale%"
In controller:
/**
*
* #Route(
* "/", name="home_cs",
* defaults={"_locale":"%locale%"}
* )
* #Route(
* "/{_locale}/", name="home",
* requirements={"_locale":"%app_locales%"}
* )
*
*/
public function indexAction(Request $request) {
return $this->render('home/index.html.twig');
}
Template header.html.twig:
<select class="selectpicker pull-right lang" data-width="fit">
<option data-content='<span class="flag-icon flag-icon-cz"></span>' {% if app.request.getLocale() == 'cs' %}selected{% endif %} >cs</option>
<option data-content='<span class="flag-icon flag-icon-us"></span>' {% if app.request.getLocale() == 'en' %}selected{% endif %} >en</option>
</select>

Twig_Error_Runtime: An exception thrown during the rendering of a template

I have URL error:
link rel="alternate" type="application/atom+xml" title="Latest Jobs"
href="{{ url('job', {'_format': 'atom'}) }}" />
Routing.yml file:
job_job:
resource: "#JobBundle/Resources/config/routing/job.yml"
prefix: /job
job_homepage:
path: /
defaults: { _controller: JobBundle:Default:index }
This what my job.yml contains -
(I use in path "job_homepage" , in url I use "job" , but when I'm trying to run show action or edit action it work correctly)
job_index:
path: /
defaults: { _controller: "JobBundle:Job:index" }
methods: GET
job_show:
path: /{id}/show
defaults: { _controller: "JobBundle:Job:show" }
methods: GET
job_new:
path: /new
defaults: { _controller: "JobBundle:Job:new" }
methods: [GET, POST]
job_edit:
path: /{id}/edit
defaults: { _controller: "JobBundle:Job:edit" }
methods: [GET, POST]
job_delete:
path: /{id}/delete
defaults: { _controller: "JobBundle:Job:delete" }
methods: DELETE
I use http://127.0.0.1:8000/job/ to run my project
You dont have a route for job in your routing file.
Should be something like:
link rel="alternate" type="application/atom+xml" title="Latest Jobs" href="{{ url('job_homepage', {'_format': 'atom'}) }}" />
Or if you have different named routes in "#JobBundle/Resources/config/routing/job.yml" use one of those. But the error is pretty clear, you dont have a route named job

symfony2 demo application change homepage

I learn a symfony2 and i would try to change route to start page in symfony demo application (blog). Instead FrameworkBundle:Template:template controller with static page default/homepage.html.twig i want to change route to AppBundle:Blog:index but i have following error:
Controller "AppBundle\Controller\BlogController::indexAction()" requires that you provide a value for the "$page" argument (because there is no default value or because there is a non optional argument after this one).
And there is a methods code:
/**
* #Route("/", name="blog_index", defaults={"page" = 1})
* #Route("/page/{page}", name="blog_index_paginated", requirements={"page" : "\d+"})
*/
public function indexAction($page)
{
$query = $this->getDoctrine()->getRepository('AppBundle:Post')->queryLatest();
$paginator = $this->get('knp_paginator');
$posts = $paginator->paginate($query, $page, Post::NUM_ITEMS);
$posts->setUsedRoute('blog_index_paginated');
return $this->render('blog/index.html.twig', array('posts' => $posts));
}
app/config/routing.yml
app:
resource: #AppBundle/Controller/
type: annotation
prefix: /{_locale}
requirements:
_locale: %app_locales%
defaults:
_locale: %locale%
homepage:
path: /{_locale}
requirements:
_locale: %app_locales%
defaults:
_controller: AppBundle:Blog:index
#_controller: FrameworkBundle:Template:template
#template: 'default/homepage.html.twig'
_locale: "%locale%"
I know, i can change in argument "$page = 1" but i think its ugly fix. Anyone can help me?
You can pass default parameter values with the defaults key:
homepage:
path: /{_locale}
requirements:
_locale: %app_locales%
defaults:
_controller: AppBundle:Blog:index
_locale: "%locale%"
page: 1
You can try with this annotation
/**
* #Route(
* path = "/page/{page}",
* name = "blog_index",
* defaults = {"page" = 1},
* requirements={"page" : "\d+"}
* )
*/

Categories