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.

15

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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