Tuesday, February 22, 2022

[FIXED] Pass constant in CakePHP 3 routing

Issue

In my CakePHP 3 application I have a route configured as below

$routes->connect(
        '/search-cars-for-dealers/:id',
        [
            'controller' => 'Cars',
            'action' => 'view',
        ],
        [
            'pass' => ['id', 'searchCarsForDealers']
        ]
    );

As you can see, I am trying to pass two parameters to the controller action. The first being id which is obtained from the original request URL and the second is a constant string - searchCarsForDealers

However, Cake doesnt pass the constant string. It only passes id and passes NULL for the second parameter. So my question is - how can I pass constant strings based on the routing URL?


Solution

If you want to pass further parameters, then you have to define them in the $defaults argument, ie

$routes->connect(
    '/search-cars-for-dealers/:id',
    [
        'controller' => 'Cars',
        'action' => 'view',
        'searchCarsForDealers'
    ],
    [
        'pass' => ['id']
    ]
);

That way searchCarsForDealers will end up as the second argument passed to the view action.

It should be noted that this will affect reverse routing, so that you cannot use URL arrays like

[
    'controller' => 'Cars',
    'action' => 'view',
    123
]

anymore, but have to define the id value as a named argument, and also add the searchCarsForDealers string, like

[
    'controller' => 'Cars',
    'action' => 'view',
    'id' => 123,
    'searchCarsForDealers'
]

See also Cookbook > Routing > Connecting Routes



Answered By - ndm

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.