Answer the question
In order to leave comments, you need to log in
How to generate Yii2 createUrl address?
Hello. The crux of the matter is as follows. I have a table: content with fields id, name, slug. In the table I am going to store dynamically created pages. In the slug field, I store the URL of the page.
Installed pure Yii2. In config/web.php specified:
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'/' => 'page/index',
['class' => 'app\components\CarUrlRule', 'connectionID' => 'db'],
],
]
namespace app\controllers;
use Yii;
use yii\web\Controller;
use yii\helpers\Url;
class ModuleController extends Controller
{
public function actionIndex()
{
return $this->render('index');
}
}
namespace app\components;
use yii\web\UrlRule;
class CarUrlRule extends UrlRule
{
public $connectionID = 'db';
public function init()
{
if ($this->name === null) {
$this->name = __CLASS__;
}
}
public function createUrl($manager, $route, $params)
{
if ($route === 'page/index') {
if (isset($params['manufacturer'], $params['model'])) {
return $params['manufacturer'] . '/' . $params['model'];
} elseif (isset($params['manufacturer'])) {
return $params['manufacturer'];
}
}
return false; // это правило не подходит
}
public function parseRequest($manager, $request)
{
$pathInfo = $request->getPathInfo();
if (preg_match('%^(\w+)(/(\w+))?$%', $pathInfo, $matches)) {
// check $matches[1] and $matches[3] to see
// if they match a manufacturer and a model in the database
// If so, set $params['manufacturer'] and/or $params['model']
// and return ['car/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