Answer the question
In order to leave comments, you need to log in
CNC Yii2, passing GET parameters, how to arrange?
In Yii, you used to write like this:
'urlManager'=>array(
'showScriptName'=>false,
'urlFormat' => 'path',
),
'urlManager'=>[
'class'=>'yii\web\UrlManager',
'showScriptName'=>false,
'enablePrettyUrl' => true,
],
Answer the question
In order to leave comments, you need to log in
Decision:
'rules' => [
['class' => 'app\components\CarUrlRule', 'connectionID' => 'db'],
],
<?php
namespace app\components;
use yii\web\UrlRule;
class CarUrlRule extends UrlRule
{
public $connectionID = 'db';
public $pattern = 'car';
public $route = 'car';
public function createUrl($manager, $route, $params)
{
if ($route === 'car/index') {
if (isset($params['manufacturer'], $params['model'])) {
return $params['manufacturer'] . '/' . $params['model'];
} elseif (isset($params['manufacturer'])) {
return $params['manufacturer'];
}
}
return false; // this rule does not apply
}
public function parseRequest($manager, $request)
{
$pathInfo = $request->getPathInfo();
$segs=explode('/',$pathInfo.'/');
$data = array();
$n=count($segs);
for($i=0;$i<$n-1;$i+=2){
if($segs[$i]==='')
continue;
$value = $segs[$i+1];
if($m=preg_match_all('/\[(.*?)\]/',$segs[$i],$matches)){
$name=substr($segs[$i],0,$pos);
for($j=$m-1;$j>=0;--$j)
if($matches[1][$j]==='')
$value=array($value);
else
$value=array($matches[1][$j]=>$value);
$data[$name]=$value;
}
else
$data[$segs[$i]]=$value;
}
return ['site/index', $data];
}
}
There is a simpler solution, in the url manager config it looks something like this:
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'<controller>/<action>' => '<controller>/<action>',
'site/hello/<name:\w+>' => 'site/hello',
]
],
EXAMPLE:
go to /site/index/c/1/b/2
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'' => 'site/index', // сделает главную страницу сайтконтроллера чистой без слэшей и экшенов
'site/index/<c:\d+>/<b:\d+>' => 'site/index', // если верхнее правило оставить можно вот так обработать http://example.ru/1/2 - d+ - digital - обрабатывает только цифры
...
],
RESULT:
we are in the index action of the site controller, getting an array GET [c=>1,b=>2]
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'' => 'site/index',
'site/index/<param:\w+>/<c:\d+>/<params:\w+>/<b:\d+>' => 'site/index',
'site/index/<param:\w+>/<c:\d+>/<params:\w+>/<b:\d+>.html' => 'site/index', // с преффиксом .html
// analog -> http://example.ru/site/index?param=c&c=1¶ms=b&b=2
// analog -> http://example.ru/site/index/c/1/b/2
// preffix -> http://example.ru/site/index/c/1/b/2.html
...
],
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question