Это старая версия документа!
Документация по Yii 2 Framework
Configuration
URL Management
echo \Yii::$app->urlManager->createUrl(['site/page', 'id' => 'about']); // /index.php/site/page/id/about/ echo \Yii::$app->urlManager->createUrl(['date-time/fast-forward', 'id' => 105]) // /index.php?r=date-time/fast-forward&id=105 echo \Yii::$app->urlManager->createAbsoluteUrl('blog/post/index'); // http://www.example.com/index.php/blog/post/index/
Конфигурация
<?php return [ // ... 'components' => [ 'urlManager' => [ 'enablePrettyUrl' => true, 'showScriptName' => false, 'enableStrictParsing' => true, 'suffix' => '.html', 'rules' => [ '<action:(login|logout|about)>' => 'site/<action>', // ... ['class' => 'app\components\CarUrlRule', 'connectionID' => 'db', ...], ], ], ], ];
Url
yii\helpers\Url::toRoute
echo Url::toRoute([''], $schema = false); // currently active route echo Url::toRoute(['view', 'id' => 'contact'], $schema = false); // same controller, different action echo Url::toRoute(['post/index'], $schema = false); // same module, different controller and action echo Url::toRoute(['/site/index'], $schema = false); // absolute route no matter what controller is making this call echo Url::toRoute(['post/read', 'id' => 100, '#' => 'title'], $schema = false)
echo Url::toRoute('', $schema = false); // currently active route echo Url::toRoute('post/index', $schema = false); // same module, different controller and action echo Url::toRoute('/site/index', $schema = false); // absolute route no matter what controller is making this call
yii\helpers\Url::to
echo Url::to('', $schema = false); // currently active route echo Url::to('post/index', $schema = false); // same module, different controller and action echo Url::to('/site/index', $schema = false); // absolute route no matter what controller is making this call
echo Url::to('@web', $schema = false); echo Url::canonical(); // get canonical URL for the curent page echo Url::home(); // get home URL echo Url::remember(); // save URL to be used later echo Url::previous(); // get previously saved URL
- $schema = true - Абсолютный адрес
- $schema = 'https' - Указание на испоользование шифрованного протокола
Синоним для yii\helpers\Url::toRoute
echo Url::to([''], $schema = false); // currently active route echo Url::to(['view', 'id' => 'contact'], $schema = false); // same controller, different action echo Url::to(['post/index'], $schema = false); // same module, different controller and action echo Url::to(['/site/index'], $schema = false); // absolute route no matter what controller is making this call echo Url::to(['post/read', 'id' => 100, '#' => 'title'], $schema = false)
Примеры использоватия можно глянуть в тестах https://github.com/yiisoft/yii2/blob/master/tests/unit/framework/helpers/UrlTest.php
yii\helpers\Html::url (old)
echo Html::url(['']); // currently active route echo Html::url(['view', 'id' => 'contact']); // same controller, different action echo Html::url(['post/index']); // same module, different controller and action echo Html::url(['/site/index']); // absolute route no matter what controller is making this call echo Html::url(['post/read', 'id' => 100, '#' => 'title'])
echo Html::url(''); // currently active route echo Html::url('post/index'); // same module, different controller and action echo Html::url('/site/index'); // absolute route no matter what controller is making this call
вместо старых методов нада использовать yii\helpers\Url::to
Примеры использоватия можно глянуть в тестах https://github.com/yiisoft/yii2/blob/master/tests/unit/framework/helpers/UrlTest.php
createUrl
echo $this->createUrl([''], $schema = null); // currently active route echo $this->createUrl(['view', 'id' => 'contact'], $schema = null); // same controller, different action echo $this->createUrl(['post/index'], $schema = null); // same module, different controller and action echo $this->createUrl(['/site/index'], $schema = null); // absolute route no matter what controller is making this call echo $this->createUrl(['post/read', 'id' => 100, '#' => 'title'], $schema = null)
echo $this->createUrl('', $schema = null); // currently active route echo $this->createUrl('post/index', $schema = null); // same module, different controller and action echo $this->createUrl('/site/index', $schema = null); // absolute route no matter what controller is making this call
createAbsoluteUrl (old)
Усли $this - это yii\web\Controller
echo $this->createAbsoluteUrl([''], $schema = null); // currently active route echo $this->createAbsoluteUrl(['view', 'id' => 'contact'], $schema = null); // same controller, different action echo $this->createAbsoluteUrl(['post/index'], $schema = null); // same module, different controller and action echo $this->createAbsoluteUrl(['/site/index'], $schema = null); // absolute route no matter what controller is making this call echo $this->createAbsoluteUrl(['post/read', 'id' => 100, '#' => 'title'], $schema = null)
вместо старых методов надо использовать yii\helpers::toRoute
Усли $this - это yii\web\Controller
echo $this->createAbsoluteUrl('', $schema = null); // currently active route echo $this->createAbsoluteUrl('post/index', $schema = null); // same module, different controller and action echo $this->createAbsoluteUrl('/site/index', $schema = null); // absolute route no matter what controller is making this call
вместо старых методов надо использовать yii\helpers::toRoute
Request
GET
Yii::$app->request->get(); Yii::$app->request->getQueryParams(); Yii::$app->request->getQueryParam('File'); Yii::$app->request->get('File');
POST
Yii::$app->request->post(); Yii::$app->request->getBodyParams(); Yii::$app->request->getBodyParam('File'); Yii::$app->request->post('File');
View
CSS
$this->registerCssFile();
JS
$this->registerJsFile();
Вставка кода внутри представления
В примере производится вставка JS кода из assets c применением переменной в скрипте JS_FABRIC_CAR_URL
$this = Yii::$app->view;
<?php $this->registerJs('var JS_FABRIC_CAR_URL = "' . Html::url(['/core/ajax/fabric-car']) . '";', View::POS_HEAD, 'js-fabric-car-url'); $publish = Yii::$app->assetManager->publish(Yii::getAlias('@app/modules/core/assets/js')); $this->registerJsFile($publish[1] . '/block-select-car.js', [yii\web\JqueryAsset::className()], ['position'=>View::POS_END]); ?>
assetManager
'components' => [ 'assetManager' => [ 'class' => 'yii\web\AssetManager', 'forceCopy' => true, ], ],
- forceCopy - Включает постоянное обновление асетов
через ajaxSetup
Добавление csrfToken в Ajax запрос (Yii2)
$js_global_variables = ' $.ajaxSetup({ data: ' . \yii\helpers\Json::encode([ \yii::$app->request->csrfParam => \yii::$app->request->csrfToken, ]) . ' });' . PHP_EOL; $this->registerJs($js_global_variables, yii\web\View::POS_HEAD, 'js_global_variables');
или через header
$js_global_variables = ' $.ajaxPrefilter(function( options ) { if ( !options.beforeSend) { options.beforeSend = function (xhr) { xhr.setRequestHeader("HTTP_X_CSRF_TOKEN", ' . \yii::$app->request->csrfToken .'); } } });' . PHP_EOL; $this->registerJs($js_global_variables, yii\web\View::POS_HEAD, 'js_global_variables');
или через JQuery
$.ajax({ url: 'http://site?controller/action', type: 'post', data: {payload: payload, _csrf: yii.getCsrfToken()}, dataType: 'json', }).success(function(response) { });