A
A
A1eksandr2015-09-03 02:24:07
Yii
A1eksandr, 2015-09-03 02:24:07

Yii2 How to implement correctly, adding to all links the parameter - city?

Tell me how easier it is to implement the parameter substitution - city to all urls.
Let's say I wrote the following rules

[
                    'pattern' => '<city:\w+>/<controller>/<action>/<id:\d+>',
                    'route' => '<controller>/<action>',
                    'suffix' => ''
                ],
                [
                    'pattern' => '<city:\w+>/<controller>/<action>/',
                    'route' => '<controller>/<action>',
                    'suffix' => ''
                ],
                [
                'pattern' => '<controller>/<action>/<id:\d+>',
                'route' => '<controller>/<action>',
                'suffix' => ''
                ],

At the same time, I set the Url like this:
$city = 'Moscow' // допустим город задан Москва.
$url = Url::toRoute(['/my-controller/my-action', 'id' => 45, 'city' => $city);

This works, but I have to add the city parameter to all Url::toRoute calls, which is not convenient. Maybe there is a way to set parameters in the default route? Or maybe there is another way to solve this problem. There are thoughts to replace Url::toRoute with your own method, but this option is also not very popular.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
A1eksandr, 2015-09-03
@A1eksandr

I solved it by extending the urlManager class and overriding the createUrl method

class MyUrlManager extends UrlManager
{

    public function createUrl($params)
    {

        if(Yii::$app->params['city'])
            $params['city'] = Yii::$app->params['city'];

        return parent::createUrl($params);

    }


}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question