I have just started using Symfony and I am having a routing problem. Here is the routing fromt the controller:
/**
* @Route("/social/{name}/", name="_speed1")
* @Route("/social/drivers/")
* @Route("/social/drivers/{name}/", name="_driver")
* @Route("/social/", name="_speed")
* @Template()
*/
public function unlimitedAction()
{
If I go to speed/social/ or speed/social/bob or speed/social/drivers/ or speed/social/drivers/bob all of those pages render with no problem. However I need the name being passed in so I changed
public function unlimitedAction()
{
to
public function unlimitedAction($name)
{
If I go to speed/social/drivers/ or speed/social/drivers/bob it returns fine. However, if I go to speed/social/ then I get the following error:
Controller "MyBundle\Controller\DefaultController::unlimitedAction()"
requires that you provide a value for the "$name" argument (because there is
no default value or because there is a non optional argument after this one).
I can’t understand why it works for one route but not the other.
So my question is, how can I acheive my routing so that I can go to:
speed/social/
speed/social/drivers/
speed/social/drivers/bob
And be able to pass the variable to the action without error.
Thanks!
To answer your question: you have to provide a default value for
nameparameter, for each route without the{name}parameter in the url. I can’t test it right now and I can’t remember the syntax when using annotations, but should be something like this:This way you should be able to call
/social/and/social/fooas well as/social/drivers/and/social/drivers/foo.But, really, this is not the right way to go. Just define more actions, each binded to a single route:
As a general rule, each method (each action) should be focused to do just one thing and should be as short as possible. Use services and make your controllers do what they are supposed to do: understand user input, call services and show views.