E
E
Evgenya-k22020-10-09 11:25:44
Yii
Evgenya-k2, 2020-10-09 11:25:44

How to setup UrlManager in Yii2 with same parameter name for different rotes?

Good afternoon!

I set up links in the project on yii2. It is necessary that the ['product/view', 'alias' => $alias]link opens http://localhost/<alias>along the route ['news-category/view', 'alias' => $alias], http://localhost/<alias>and the ['stat-page/view', 'alias' => $alias]link with url also opens along the route http://localhost/<alias>. All slugs are unique.
URLManager:

'urlManager' => [
            'enablePrettyUrl' => true,
            'enableStrictParsing' => true,
            'showScriptName' => false,
            'rules' => [
                '/' => 'site/index',
                'site/feedback-create' => 'site/feedback-create',
                'products' => 'category/index',
                'products/<alias>' => 'category/view',
                '<alias>' => 'product/view',
                '<alias>' => 'news-category/view',
                '<category>/<alias>' => 'news/view',
                '<alias>' => 'stat-page/view',
            ],
        ],


Opens only by the last rule. I can’t figure out how the UrlManager works and how to make one pattern for different routes?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgenya-k2, 2020-10-15
@Evgenya-k2

Understood. Inherited class from UrlRule, overridden methods createUrl()and parseRequest().

public function createUrl($manager, $route, $params) 
{
        if ($route == 'news-category/view' || $route == 'stat-page/view') {
            if (isset($params['alias'])) {
                return '/' . $params['alias'];
            }
        }

        return false;
}

public function parseRequest($manager, $request)
{
        $pathInfo = $request->getPathInfo();
        $pathArray = explode('/', $pathInfo);
        $params['alias'] = $pathInfo;
        $alias = array_pop($pathArray);
        if (StatPage::find()->published()->byAlias($alias)->one()) {
            return ['stat-page/view', $params];
        } elseif (NewsCategory::find()->published()->byAlias($alias)->one()) {
            return ['news-category/view', $params];
        }

        return false;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question