Home > Enterprise >  CakePHP: How to allow a RESTful view action (get) to accept two params?
CakePHP: How to allow a RESTful view action (get) to accept two params?

Time:06-08

After applied auto RESTful routes using $routes->resources('ProcessoJudicial')

I would like to allow my view method to accept two or more parameters (by domains rules), something like:

public function view(string $cnj, string $sigla_tribunal = null) {
        ...
}

Works well using this URI:

http://localhost/myapp/processo_judicial/22/

But when I try two params like:

http://localhost/myapp/processo_judicial/22/11/

I got an error:

Error: Your routing resulted in Processo_judicial as a controller name. 
Ensure that your URL /processo_judicial/22/11/ is using the same inflection style as your routes do. By default applications use DashedRoute and URLs should use - to separate multi-word controller names.

CodePudding user response:

Resource routes have a fixed URL format that doesn't accept trailing arguments, you can't append values to them:

HTTP format URL.format Controller action invoked
GET /recipes.format RecipesController::index()
GET /recipes/123.format RecipesController::view(123)
POST /recipes.format RecipesController::add()
PUT /recipes/123.format RecipesController::edit(123)
PATCH /recipes/123.format RecipesController::edit(123)
DELETE /recipes/123.format RecipesController::delete(123)

Cookbook > Routing > RESTful Routing

There's some configuration that can be applied to change things up, namely the connectOptions option (which basically ends up as the 3rd argument of RouteBuilder::connect()) that allows to for example define passed parameters, and the map option under which custom paths for actions can be defined.

Here's an example that would override the built-in view route config, and define an additional route element to be passed:

$routes->resources('ModelName', [
    'connectOptions' => [
        'acronym' => '[a-zA-Z] ',
        'pass' => ['id', 'acronym'],
    ],
    'map' => [
        'view' => [
            'action' => 'view',
            'method' => 'GET',
            'path' => '{id}/{acronym}',
        ],
    ],
]);

If that is an outlier, then it's probably fine to do it this way. If you however have to do that for many more routes, then you should consider ditching the resources() shorthand, and instead create all the required routes on your own.

See also

  • Related