Answer the question
In order to leave comments, you need to log in
Have I configured the routing correctly?
Hello. It was necessary to configure custom routing for filters on the page.
A filter is a form that passes $_GET parameters according to the Yii2 rules for a model.
Those. when applying the filter, the url looks something like this: index.html?RoutesSearch[id_district]=9&RoutesSearch[id_region]=10&page=4
Required: routes/district/yuzhnyj/region/krym/index.html?page=3
As implemented. First of all redirect to the correct URL. I did it in the controller in the beforeAction() method
public function beforeAction($action)
{
if ($action->id == 'index' && stripos(Yii::$app->request->absoluteUrl, 'RoutesSearch')) {
$redirectUrl = Url::base(true).'/routes';
$params = Yii::$app->request->get('RoutesSearch');
if (isset($params['id_district'])) {
$model = District::findOne($params['id_district']);
if ($model)
$redirectUrl .= '/district/'.$model->URI;
}
if (isset($params['id_region'])) {
$model = Regions::findOne($params['id_region']);
if ($model)
$redirectUrl .= '/region/'.$model->URI;
}
if (isset($params['type_id'])) {
$model = RouteTypeNew::findOne($params['type_id']);
if ($model)
$redirectUrl .= '/type/'.$model->URI;
}
if (isset($params['period'])) {
$model = Month::findOne($params['period']);
if ($model)
$redirectUrl .= '/month/'.$model->URI;
}
$redirectUrl .= '/index.html';
if (!empty(Yii::$app->request->get('page'))) {
$redirectUrl .= '?page='.Yii::$app->request->get('page');
}
header('HTTP/1.1 301 Moved Permanently');
header('Location: '.$redirectUrl);
exit();
}
return true;
}
class MainFiltersRule implements UrlRuleInterface
{
public function createUrl($manager, $route, $params)
{
return false;
}
public function parseRequest($manager, $request)
{
$pathInfo = $request->getPathInfo();
$partsUrl = explode('/' ,$pathInfo);
if ($partsUrl[0] == 'routes') {
if (in_array('district', $partsUrl)) {
$model = District::find()->where(['URI' => $partsUrl[array_search('district', $partsUrl) + 1]])->one();
$params['RoutesSearch']['id_district'] = $model->id;
}
if (in_array('region', $partsUrl)) {
$model = Regions::find()->where(['URI' => $partsUrl[array_search('region', $partsUrl) + 1]])->one();
$params['RoutesSearch']['id_region'] = $model->id;
}
if (in_array('type', $partsUrl)) {
$model = RouteTypeNew::find()->where(['URI' => $partsUrl[array_search('type', $partsUrl) + 1]])->one();
$params['RoutesSearch']['type_id'] = $model->id;
}
if (in_array('month', $partsUrl)) {
$model = Month::find()->where(['URI' => $partsUrl[array_search('month', $partsUrl) + 1]])->one();
$params['RoutesSearch'] = $model->id;
}
return ['routes/index', $params];
}
return false;
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question