4

I want define a simple controller action, which receive optional argument:

<?php

namespace Drupal\hello\Controller;

class SimpleCallback extends ControllerBase
{
    public function sayHiAction($name = 'there')
    {
        return new Response('Hi ' . $name, 200);
    }
}
?>

If I define the routing like this

# file @hello.routing.yml
hello.sayHi:
  path: '/hello/{name}'
  defaults:
    _title: 'Say Hi'
    _content: 'Drupal\hello\Controller\SimpleCallback::sayHiAction'
  requirements:
      _permission: 'access content'

GET /hello just gives me 404 response.

Follow official documentation, I updated my route:

# file @hello.routing.yml
hello.sayHi:
  path: '/hello/{name}'
  defaults:
    _title: 'Say Hi'
    _content: 'Drupal\hello\Controller\SimpleCallback::sayHiAction'
    custom_arg: 'there'
  requirements:
      _permission: 'access content'

But nothing changed.

1 Answer 1

20

The docs you link to say:

Finally, if any static arguments should be passed to the controller, provide those in the defaults array as well. Name them to match the arguments of your controller method. See below.

Emphasis mine.

So your code should be:

# file @hello.routing.yml
hello.sayHi:
  path: '/hello/{name}'
  defaults: 
    _title: 'Say Hi'
    _content: 'Drupal\hello\Controller\SimpleCallback::sayHiAction'
    name: 'there'
  requirements:
      _permission: 'access content'

See also Required and Optional Placeholders in the Symfony routing docs.

1
  • "Name them to match the arguments of your controller method". Yeah there's some magic that won't work if you name it differently.
    – simesy
    Feb 26 at 22:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.