You can set default parameters in RequestContext.
When Symfony generates an URL, it uses values in this order:
See Symfony\Component\Routing\Generator\UrlGenerator::doGenerate
:
$mergedParams = array_replace($defaults,
$this->context->getParameters(),
$parameters);
- user supplied parameters to generateUrl() function
- context parameters
- route defaults
You can set the context parameters in a request event listener to override Route defaults:
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Routing\RouterInterface;
class RequestListener
{
private $_router;
public function __construct(RouterInterface $router)
{
$this->_router = $router;
}
public function onRequest(GetResponseEvent $event)
{
$context = $this->_router->getContext();
if (!$context->hasParameter('year')) {
$context->setParameter('year', date('Y'));
}
}
}
Service configuration:
<service id="my.request_listener"
class="MyBundle\EventListener\RequestListener">
<argument id="router" type="service"/>
<tag name="kernel.event_listener"
event="kernel.request" method="onRequest" />
</service>
It depends on a use case, if you want to use dynamic default just to generate url, use code above. If you want your controller to dynamically pick right default value before executing action, you could probably use 'kernel.controller' event and set request attributes if not present.
kernel.request
listener and using the RouterContext is a very smart solution. Thanks! – Comyns