Drupal Answers is a question and answer site for Drupal developers and administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
up vote 4 down vote accepted

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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