Problem to solve
Is it possible in Symfony 2, define routes with 'intermediate' optional parameters. I'll use other question data, for supporting me using the same style, for example:
- localhost/param 1/param 2/param 3/param 4
Example
- localhost/param 1/param 4
- localhost/param 2/param 4
Because I have a problem where none of my parameters should be mandatory, and different logics come into play, subordinated to those activated parameters.
Until now if I don't set like this:
- localhost/param 1/param 2/...
(missing: param 3/param 4)
I can't play with intermediate parameters and it's a less flexible solution. If previous parameters to optional ones (all of them) aren't specify I can't achieve this. I don't wan't to create additional routes for the same context if it has a cleaner sight.
This is my route context:
zk_time_download_with_all_parameters:
pattern: /download/{format}/{id}/{start_date}/{end_date}
defaults: { _controller: ZkTimeBundle:Empleado:download, format: txt, id: %employeeId%, start_date: %start_date%, end_date: %end_date% }
requirements:
id: -?\d+
start_date: ^((\d{4})[/|-]?(\d{2})[/|-]?(\d{2}))*|(\d{2})[/|-]?(\d{2})[/|-]?(\d{4})$
end_date: ^((\d{4})[/|-]?(\d{2})[/|-]?(\d{2}))*|(\d{2})[/|-]?(\d{2})[/|-]?(\d{4})$
format: txt|xml|pdf
These are the criterias I pursuit:
- Download the data in several formats (Optional: 'txt' by default)
- Download data for a specific Id or whitout it (Optional: I peek all I find for the default period: daily or monthly)
- Specify start OR end, start AND end (Optional both dates)
I check in my controller the route empty parameters and create the corresponding queries (by default).
Parameters initialized in my Extension class:
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
//Route: /marca/{start_date}/{end_date}
$today = date('d-m-Y');
$today_object = new \DateTime($today);
$total_days = $today_object->format('t');
$month_start = $today_object->format('Y-m-1');
$month_end = $today_object->format('Y-m-' . $total_days);
$container->setParameter('month_start', $month_start);
$container->setParameter('month_end', $month_end);
$container->setParameter('start_date', $today);
$container->setParameter('end_date', $today);
$container->setParameter('format', 'txt');
$container->setParameter('employeeId', 0);
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
$loader->load('services.yml');
}