lkartono
lkartono

Reputation: 2393

zend framework get id in /delete/2

I'm actually using zend, and I wonder how to get the id in such url :

/delete/2

I know I can do it using :

// if URL is /delete/id/2
$request->getParam('id');

But what I want is to have url like the first one /delete/2 which sounds more logical to me.

Ideas?

Thanks for your help

Upvotes: 0

Views: 1356

Answers (2)

mohamed elbou
mohamed elbou

Reputation: 1857

Try this: add the following function to your Bootstrap.php

protected function _initRoute(){
    $this->bootstrap ('frontcontroller');
    $front = $this->getResource('frontcontroller');
    $router = $front->getRouter();
    $deleteRoute = new Zend_Controller_Router_Route(
    'delete/:id',
    array(
        'controller' => '{enter-your-controller-name-here}',
        'action'     => '{enter-your-action-name-here}'
        )
    );
    $router->addRoute('delete', $deleteRoute);
}

Don't forget to replace {enter-your-controller-name-here} with controller name and {enter-your-action-name-here} with action name.

With this code added, $request->getParam('id'); should work just fine.

Upvotes: 0

Config
Config

Reputation: 1692

I think you should be able to solve this kind of problem using routes. You can create a route for

/delete/2

by adding this to for example your config.ini file:

[production]
routes.delete.route = "delete/:id"
routes.delete.defaults.controller = delete
routes.delete.defaults.action = index 
routes.delete.id.reqs = "\d+"

Here you specify the URL to match, in which words starting with a colon : are variables. As you can see, you can also set requirements on your variables regex-style. In your example, id will most likely be one or more digits, resulting in a \d+ requirement on this variable.

This route will point the url to the index action of the delete controller and sets id as a GET-var. You can alter this .ini code to suit your specific needs.

The routes can be added by putting the following code inside your bootstrap:

$config = new Zend_Config_Ini('/path/to/config.ini', 'production');
$router = new Zend_Controller_Router_Rewrite();
$router->addConfig($config, 'routes');

See the docs for more information: here for the general documentation and here for the .ini approach I just described.

Upvotes: 1

Related Questions