I have a problem with my Symfony2.2 beta routes. (symfony-2-2-0-beta-1)
I use annoations routes like this:
#Route("/form/{id}", defaults={"id"=0}, requirements={"id"="\d+"});
And the error is:
An exception has been thrown during the rendering of a template ("Parameter "id" for route "[...]_form" must match "\d+" ("" given).") in [...]:form.html.twig at line 1.
The line 1 is:
{{ path("[...]_form") }}
I think the route is correct, because I define "id=0" as default.
And in Symfony2.1 the same code works.
Have you tried setting the default in your action and taking it out of the annotation?
/**
* #Route("/form/{id}", name="my_form", requirements={"id"="\d+"});
*/
public function myFunction($id = 0){
...
I believe this is one of the changes in Symfony 2.2 although I haven't tried it yet. http://symfony.com/blog/new-in-symfony-2-2-small-things-matter#defining-default-values-when-using-the-route-annotation
You can try
requirements:
id: \S|\d+
Related
I am in charge of upgrading easyadmin bundle on an app that was previously built using symfony v4.4.19. Initially we had: easycorp/easyadmin-bundle v2.3.12. Then, we decided to upgrade the easyadmin bundle to v3 because we faced some issues when enabling/disabling a boolean property from the list view.
When I was using the v2 :
php bin/console debug:router showed a route called easyadmin with a path /myworkshop/ .
I had no Dashboard controller nor NecklaceCrudController, I simply had a controlller called
AccessoriesController.php with several actions like deleteAction that is executed when the user
deletes an entity, editAction when the user edits an entity, SearchAction ...
In the deleteAction there is this line of code:
return $this->redirect($this->generateUrl('easyadmin', array('action' => 'list', 'entity'=> $this->entity['name'])));
so the url would become something like this
/myworkshop/?action=list&entity=necklace
To open the easy admin interface I have to click on a menu link whose link is :
->createItem('Visit my workshop', ['route' => 'easyadmin']);
When I open this interface /references, I get the list of the different entities in my app, if
I select one, I see the list view and I can edit one entity successfully but I cannot
enable/disable boolean properties from the list view as mentioned earlier.
We specified /myworkshop instead of /admin in app>config>routing.yml
# easy admin
easy_admin_bundle:
resource: "#myShop/Controller/AccessoriesController.php"
type: annotation
prefix: /myworkshop```
- A custom css was successfully employed in : app>config>config.yml
easy_admin:
design:
assets:
css:
- 'bundles/css/easyadmin.css
When I upgraded to v3:
php bin/console debug:router showed a route called myshop_admin_dashboard_index (which was
automatically generated) with a path /easyadmin.
Dashboard controller and NecklaceCrudController were created, The DashboardController only has configureCrud() and configureMenuItems() functions. The latter contains the links yield MenuItem::linkToCrud . Question 1 : In version 2 no menu links where created explicitely like here, so I was wondering how was the complete list of entities correctly showing up on my application interface?
In DashboardController there is no index () function nor a route nor a link just configureCrud() and configureMenuItems() functions.
I want to keep the AccessoriesController.php with his several actions but now, with the new route and path, it is completely being ignored. Question 2 : Is there something that I have to change in the generateUrl part? can someone give me an example of what this will become if I opt for adminUrlgenerator like I read in the documentation?
The routing.yml file remains the same however, my easyadmin interface appears only when visiting this link /easyadmin instead of /myworkshop . Question 3: I want to keep the /workshop url , what should I do in addition to keeping the routing.yml as it is now?
I wish we could change myshop_admin_dashboard_index to easyadmin and /easyadmin to my /myworkshop as it was in version 2, because there are many parts in AccessoriesController where I use $this->generateUrl('easyadmin',
Question 4: The css is no longer applicable any idea why? could be related to the AccessoriesController that is not currently being taken into account.
Well, you can add the index method to your dashboard controller with route annotation to change the route
class DashboardController extends AbstractDashboardController
{
/**
* #Route("/myworkshop", name="admin")
*/
public function index(): Response
{
return $this->render('dashboard/index.html.twig');
}
You can add any route to easyadmin menu like this
class DashboardController extends AbstractDashboardController
{
public function configureMenuItems(): iterable
{
yield MenuItem::linktoRoute('Some Route', 'fa fa-info', 'route_name_here');
#...
}
}
You can add any CSS/js file too
class DashboardController extends AbstractDashboardController
{
public function configureAssets(): Assets
{
return Assets::new()
->addCssFile('build/admin.css')
->addJsFile('build/admin.js')
;
}
}
I am using Symfony5 and Twig 1.5 and want to translate the time_diff filter. My service configuration looks like this:
twig.extension:
class: Twig_Extensions_Extension_Date
arguments: ['#translator']
tags:
- { name: twig.extension }
Unfortunately I get the following error message:
Argument 1 passed to Twig_Extensions_Extension_Date::__construct() must be an instance of Symfony\Component\Translation\TranslatorInterface or null, instance of Symfony\Component\Translation\DataCollectorTranslator
The reason for this is that Twig_Extensions_Extension_Date expects Symfony\Component\Translation\TranslatorInterface but DataCollectorTranslator implements Symfony\Contracts\Translation\TranslatorInterface.
How can I pass the correct translator to Twig_Extensions_Extension_Date?
It looks like Twig-extensions was abandoned and you have to write it yourself or use another bundle (https://github.com/twigphp/Twig-extensions/issues/264).
I have a problem with the symfony routing.
For an multilanguage projekt I render a Twig template via a job queue for mailing. In this template is a link to a route that requires the "_locale" parameter with "de" or "en" for example. I use the function "{{ url('route', {'_locale': 'de'}) }}" to generate the url.
By rendering the template, I got the following error message:
[Twig_Error_Runtime]
An exception has been thrown during the rendering of a template ("Some mandatory parameters are missing ("_locale") to generate a URL for route "Route".") in "TemplatePath" at line 5.
Whats my mistake?
Thanks for help
When you are generating URL route, via CLI, the Symfony kernel is missing a HTTP Request, and a Routing->RequestContext.
Thats why, the URL generator cannot find _locale parameter.
To fix it, you must manually create a RequestContext, so, in your command:
$this->getContainer()->get('router')
->setContext(
(new RequestContext())
->setParameter('_locale', 'fr')
);
class BaseCommand extends ContainerAwareCommand
{
protected function getLocale()
{
return $this->getContainer()->get('translator')->getLocale();
}
protected function render($view, $data)
{
return $this->getContainer()->get('templating')->render($view, $data);
}
}
in command
class SomeCommand extends BaseCommand
{
...
$this->render($view, array_merge($data, ['_locale' => $this->getLocale()])
}
in view
{{url('any', {param: 'foo'}|merge(_locale is defined ? {'_locale': _locale } : {}))}}
It's necro time :)
I'm just guessing here, but there's a couple things you can try.
Can you set the locale in your command?
Set the locale for the translator bundle:
$this->getContainer()->get('translator')->setLocale('de');
Set the locale for this session:
$this->getContainer()->get('session')->setLocale('de);
Internationalized routing for Symfony 4.1 and higher
If this applies to you, try this:
url('route.de', {'_locale': 'de'}) }}"
Does your route have 'de' and 'en' set as a requirement?
/**
* Matches /route
* #Route(
* "/route/{_locale}",
* requirements={
* '_locale': 'en|de'
* },
* name="route"
* )
*/
It's an old question but this might help someone out.
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.
I have a symfony project in which I've been through my twig templates and added {% trans %}...{% endtrans %} or adding translations like {{ title|trans }} where appropriate. I've also added a messages.de.xliff file and that is working perfectly for the few translations I have tried.
Is there a way I can get a list of strings missing from my xliff file? It's quite hard to keep track of every translation as I add it. It seems like it should log a failure to get a translation in a log file somewhere, but I've been googling a while and can't find anything.
Hi Try following May Be helpful.
https://github.com/schmittjoh/JMSTranslationBundle/blob/master/Resources/doc/index.rst
Very powerful tool and definitely takes care of you problem.
This is a very crappy patch to apply in vendor/symfony that does what I need. Probably not to be run on a production server!
diff --git a/src/Symfony/Component/Translation/MessageCatalogue.php b/src/Symfony/Component/Translation/MessageCatalogue.php
index b55676f..98a5cba 100644
--- a/src/Symfony/Component/Translation/MessageCatalogue.php
+++ b/src/Symfony/Component/Translation/MessageCatalogue.php
## -128,6 +128,8 ## class MessageCatalogue implements MessageCatalogueInterface
return $this->fallbackCatalogue->get($id, $domain);
}
+ error_log('Translation not found: "' . $id . '"');
+
return $id;
}
My solution was to overwrite the Translator and MessageCatalogue classes.
Translator:
class RegisteringTranslator extends \Symfony\Component\Translation\Translator
{
protected function loadCatalogue($locale)
{
parent::loadCatalogue($locale);
if ( ! $this->catalogues[$locale] instanceof RegisteringMessageCatalogue) {
$registeringCatalogue = new RegisteringMessageCatalogue($locale);
$registeringCatalogue->addCatalogue($this->catalogues[$locale]);
$this->catalogues[$locale] = $registeringCatalogue;
}
}
}
Catalogue:
class RegisteringMessageCatalogue extends \Symfony\Component\Translation\MessageCatalogue
{
public function get($id, $domain = 'messages')
{
if ( ! $this->has($id, $domain)) {
error_log('Translation not found: "' . $id . '"');
}
return parent::get($id, $domain);
}
}
Of course you need to use the new Translator class.
Also not very nice because it uses the protected methods and properties of Translator class. But better than changing the Symfony code directly.
I know this is an old question, but I'm posting here just in case somebody still has the same problem.
Starting from Symfony 2.6, you'll find a very nice addition to the web debug toolbar that shows how many translations you're missing.
By clicking it, the profiler will display a detailed list of missing translation.
Works out of the box, without any configuration.
Normally you should be able to use the Symfony command debug:translation via app/console.
Something like this:
$ php app/console debug:translation --only-missing <locale> <Bundle Name>
A concrete example would be:
$ php app/console debug:translation --only-missing nl AppBundle
That would output:
----------- ---------- ------------------------------------------------------------------------------------------------------- ------------------------------------------
State Domain Id Message Preview (nl)
----------- ---------- ------------------------------------------------------------------------------------------------------- ------------------------------------------
missing messages Create a clean selection Create a clean selection
missing messages New Selection New Selection
missing messages login.labels.geoserver_url login.labels.geoserver_url