Answer the question
In order to leave comments, you need to log in
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',
],
],
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question