Dubby
Dubby

Reputation: 2402

Cannot route to custom action in Yii2 controller

I am building a RESTful API with Yii2 (advanced) and endpoints are working as expected apart from a custom one I need.

My urlManagerlooks like:

        'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => 
                ['class' => 'yii\rest\UrlRule', 'controller' => 'api/v1/step', 'pluralize' => false],
    ],

If I add a custom action into the StepController like so it will work just fine - Calling with http://example.com/api/v1/step/test

public function actionTest()

However if I want to pass an ID in through the path I will receive a 404 error - http://example.com/api/v1/step/test/1

public function actionTest($id)

Is there something I'm missing?

Edit: Adding notes that may help others.

My example above was simplified but what I wanted my URL to look like was like http://example.com/api/v1/step/test-by-foobar/1 with the called method to be public function actionTestByFoobar($id). However to get this to work you have to set the urlManager rule like the following which I didn't find obvious:

'api/v1/step/test-by-foobar/1' => 'api/v1/step/test-by-foobar',

Notice that the value is hyphenated, not in camel-case.

Upvotes: 1

Views: 684

Answers (1)

Francis Ngueukam
Francis Ngueukam

Reputation: 1024

With your code you can pass an id like this :

http://example.com/api/v1/step/test?id=1

But if you want to do it like this:

http://example.com/api/v1/step/test/1

You should rewrite the url like below:

'urlManager' => [
     'enablePrettyUrl' => true,
     'showScriptName' => false,
     'rules' => [
            ['class' => 'yii\rest\UrlRule', 
             'controller' => 'api/v1/step', 
             'pluralize' => false
            ],

            /* You are missing this line below */
            'api/v1/step/test/<id:\d+>' => 'api/v1/step/test'
     ]
],

Upvotes: 3

Related Questions