How to determine default date values ​​in Symfony2 routes?

If I want to create a route where the year, month, and date are variables, how can I determine if these variables are empty, should the current date be taken?

eg. like this (doesn't work for sure ...)

blog: path: /blog/{year}/{month}/{day} defaults: { _controller: AcmeBlogBundle:Blog:index, year: current_year, month: current_month day: current_day } 

I was thinking of defining two different routes, such as

 blog_current_day: path: /blog defaults: { _controller: AcmeBlogBundle:Blog:index } blog: path: /blog/{year}/{month}/{day} defaults: { _controller: AcmeBlogBundle:Blog:index } 

But if I then call blog_current_day my controller

 public function indexAction(Request $request, $year, $month, $day) { // ... } 

will throw an exception because there is no year, month, and day.

Any suggestions?

+4
source share
2 answers

Dynamic Container Options

You can set container parameters dynamically in your package extension located Acme\BlogBundle\DependencyInjection\AcmeBlogExtension , after which you can use these parameters in your routes, for example %parameter% .

Extension

 namespace Acme\BlogBundle\DependencyInjection; use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\ContainerBuilder; class AcmeBlogExtension extends Extension { public function load(array $configs, ContainerBuilder $container) { $container->setParameter( 'current_year', date("Y") ); $container->setParameter( 'current_month', date("m") ); $container->setParameter( 'current_day', date("d") ); } } 

Routing configuration

 blog: path: /blog/{year}/{month}/{day} defaults: { _controller: AcmeBlogBundle:Blog:index, year: %current_year%, month: %current_month%, day: %current_day% } 

Static Parameters

If you need only custom static parameters, you can simply add them to your config.yml .

 parameters: static_parameter: "whatever" 

... then access them again in your routing, e.g. %static_parameter% .

+10
source

You can set $year = null, $month = null, $day = null to the controller.

or possibly on a route:

 year: null, month: null, day: null, 

Then in the controller you should get the latest messages if the variables = null or messages by date.

+2
source

Source: https://habr.com/ru/post/1502014/


All Articles