How To Have A Parametized Action Or Rewrite A Param Passed To Action?


I have a controller called City and in /view/city/index.php I show a list of cities. I wish to obtain a link of this type: in which "Rome" is the param I pass to actionCity. How I can do that?


Like this:

<?php foreach ($cities as $item): ?>

echo CHtml::link($item->name, array('city/city', 'slug' => $item->slug));

<?pgp endforeach; ?>

where ‘slug’ is a field where city’s unique alias is stored.

Also you’ll need some routing rules:

'city/<slug:[\w\-_]+>' => 'city/city'

And the action’s signature is

public function actionCity($slug) {}


I’m having some trouble with to apply your suggestion.

I try to explain better.

I have this controller called CityController to whitch I would pass city name (for SEO reasons) and city id to do some CRUD in DB.

I wisth to have a link of this type:

and in actionIndex of CityController I wish to manage city_name and city_id params.

I tried to add your rule (only for city_name) but it doesn’t works.

How I can realise that?

Thank you very much for your support.

The same way, only routing rule changes.

'city/<city_name:[\w\-_]+>/<city_id:\d+>' => 'city/city'

and the action may look like this

public function actionCity($city_name, $city_id) {

    $city = City::model()->findByPk($city_id);

    //... and here's how the url is constructed

    $this->redirect(array('city/city','city_name' => $city->name, 'city_id' => $city->id));


Actually you can do many things, check the docs