mirror of
https://github.com/yiisoft/yii2.git
synced 2025-11-03 22:32:40 +08:00
Merge branch 'master' of git://github.com/yiisoft/yii2 into guide-pl
This commit is contained in:
@ -3,7 +3,7 @@
|
||||
|
||||
Yii предоставляет набор [виджетов](structure-widgets.md), которые могут быть использованы для отображения данных.
|
||||
В то время как виджет [DetailView](#detail-view) может быть использован для отображения данных по одной записи, то
|
||||
виджеты [ListView](#list-view) и [GridView](#grid-view) могут быть использованы для показа данных в виде списка иил
|
||||
виджеты [ListView](#list-view) и [GridView](#grid-view) могут быть использованы для показа данных в виде списка или
|
||||
таблицы с возможностью сортировки, фильтрации и разбивки данных постранично.
|
||||
|
||||
|
||||
@ -40,7 +40,7 @@ echo DetailView::widget([
|
||||
ListView <a name="list-view"></a>
|
||||
--------
|
||||
|
||||
Виджет [[yii\widgets\ListView|ListView]] использует для отображения информации [провайдер данных](output-data-providers.md).
|
||||
Виджет [[yii\widgets\ListView|ListView]] использует для отображения информации [провайдера данных](output-data-providers.md).
|
||||
Каждая модель отображается, используя определённый [[yii\widgets\ListView::$itemView|вид]]. Поскольку провайдер включает
|
||||
в себя разбивку на страницы, сортировку и фильтрацию, то его использование удобно для отображения информации конечному
|
||||
пользователю и создания интерфейса управления данными.
|
||||
@ -459,10 +459,9 @@ $query->andFilterWhere(['LIKE', 'author.name', $this->getAttribute('author.name'
|
||||
```
|
||||
|
||||
> Информация: В коде, что выше, использует такая же строка, как и имя зависимости и псевдонима таблицы.
|
||||
> however, when your alias and relation name
|
||||
> differ, you have to pay attention to where you use the alias and where you use the relation name.
|
||||
> A simple rule for this is to use the alias in every place that is used to build the database query and the
|
||||
> relation name in all other definitions such as `attributes()` and `rules()` etc.
|
||||
> Однако, когда ваш псевдоним и имя связи различаются, вы должны обратить внимание, где вы используете псевдоним,
|
||||
> а где имя связи. Простым правилом для этого является использование псевдонима в каждом месте, которое используется
|
||||
> для построения запроса к базе данных, и имя связи во всех других определениях, таких как `attributes()`, `rules()` и т.д.
|
||||
>
|
||||
> Например, если вы используете псевдоним `au` для связи с таблицей автора, то joinWith будет выглядеть так:
|
||||
>
|
||||
|
||||
@ -244,7 +244,7 @@ public function rules()
|
||||
Если не указать свойство `on`, то правило применяется во всех сценариях. Правило называется *активным правилом* если оно может быть применено в текущем сценарии [[yii\base\Model::scenario|scenario]].
|
||||
|
||||
Атрибут будет проверяться тогда и только тогда если он является активным атрибутом объявленным в `scenarios()` и
|
||||
связаным с одним или несколькими активными правилами, объявленными в `rules()`.
|
||||
связанным с одним или несколькими активными правилами, объявленными в `rules()`.
|
||||
|
||||
## Массовое Присвоение <span id="massive-assignment"></span>
|
||||
|
||||
|
||||
@ -294,7 +294,7 @@ use yii\helpers\Html;
|
||||
|
||||
Как видите, шаблон генерирует HTML тэги, которые присутствуют на всех страницах. Внутри секции `<body>`, шаблон выводит переменную `$content`, которая содержит результат рендеринга видов контента, который передается в шаблон, при работе метода [[yii\base\Controller::render()]].
|
||||
|
||||
Большинство шаблонов вызывают методы, аналогично тому, как это сделано в примере выше, чтобы скрипты и тэги, зарегистированные в других местах приложения могли быть правильно отображены в местах вызова (например, в шаблоне).
|
||||
Большинство шаблонов вызывают методы, аналогично тому, как это сделано в примере выше, чтобы скрипты и тэги, зарегистрированные в других местах приложения могли быть правильно отображены в местах вызова (например, в шаблоне).
|
||||
|
||||
- [[yii\base\View::beginPage()|beginPage()]]: Этот метод нужно вызывать в самом начале шаблона.
|
||||
Он вызывает событие [[yii\base\View::EVENT_BEGIN_PAGE|EVENT_BEGIN_PAGE]], которое происходит при начале обработки страницы.
|
||||
@ -516,7 +516,7 @@ $this->registerMetaTag(['name' => 'keywords', 'content' => 'yii, framework, php'
|
||||
<meta name="keywords" content="yii, framework, php">
|
||||
```
|
||||
|
||||
Обратите внимание, что при вызове метода [[yii\web\View::registerMetaTag()]] несколько раз мета тэги будут регистироваться
|
||||
Обратите внимание, что при вызове метода [[yii\web\View::registerMetaTag()]] несколько раз мета тэги будут регистрироваться
|
||||
каждый раз без проверки на уникальность.
|
||||
|
||||
Чтобы убедиться, что зарегистрирован только один экземпляр одного типа мета тэгов, вы можете указать ключ мета тэга в качестве второго
|
||||
|
||||
@ -13,7 +13,7 @@ Yii располагает несколькими средствами, приз
|
||||
Локализация и языки
|
||||
-------------------
|
||||
|
||||
В Yii приложении определены два языка: [[yii\base\Application::$sourceLanguage|исходный язык]] н [[yii\base\
|
||||
В Yii приложении определены два языка: [[yii\base\Application::$sourceLanguage|исходный язык]] и [[yii\base\
|
||||
Application::$language|язык перевода]].
|
||||
|
||||
На "исходном языке" написаны сообщения в коде приложения. Если мы определяем исходным языком английский, то
|
||||
|
||||
@ -207,8 +207,8 @@ For example,
|
||||
// "db" is a previously registered alias name
|
||||
$db = $container->get('db');
|
||||
|
||||
// equivalent to: $engine = new \app\components\SearchEngine($apiKey, ['type' => 1]);
|
||||
$engine = $container->get('app\components\SearchEngine', [$apiKey], ['type' => 1]);
|
||||
// equivalent to: $engine = new \app\components\SearchEngine($apiKey, $apiSecret, ['type' => 1]);
|
||||
$engine = $container->get('app\components\SearchEngine', [$apiKey, $apiSecret], ['type' => 1]);
|
||||
```
|
||||
|
||||
Behind the scene, the DI container does much more work than just creating a new object.
|
||||
|
||||
@ -23,7 +23,9 @@ $config = [ ... ];
|
||||
|
||||
if (YII_ENV_DEV) {
|
||||
$config['bootstrap'][] = 'gii';
|
||||
$config['modules']['gii'] = 'yii\gii\Module';
|
||||
$config['modules']['gii'] = [
|
||||
'class' => 'yii\gii\Module',
|
||||
];
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
@ -575,9 +575,8 @@ language is `ru-RU`, you may translate the view and save it as the file `views/
|
||||
whenever you call [[yii\base\View::renderFile()]] or any method that invoke this method (e.g. [[yii\base\Controller::render()]])
|
||||
to render the view `views/site/index.php`, it will end up rendering the translated view `views/site/ru-RU/index.php`, instead.
|
||||
|
||||
> Note: If the [[yii\base\Application::$language|target language]] is the same as [[yii\base\Application::$sourceLanguage|source language]],
|
||||
> view translation may still work as long as you provide a translated view. For example, if both languages are `en-US`
|
||||
> and you have both `views/site/index.php` and `views/site/en-US/index.php`, then the latter will be rendered.
|
||||
> Note: If the [[yii\base\Application::$language|target language]] is the same as [[yii\base\Application::$sourceLanguage|source language]]
|
||||
> original view will be rendered regardless of presence of translated view.
|
||||
|
||||
|
||||
## Formatting Date and Number Values <span id="date-number"></span>
|
||||
|
||||
@ -24,6 +24,9 @@ Yii Framework 2 Change Log
|
||||
- Bug #8772: ActiveQuery failed removing duplicate records after join when the resultset did not contain the pk values e.g. after grouping (cebe)
|
||||
- Bug #8900: Fixed determine active menu item with url-alias in route `\yii\widgets\Menu::isItemActive()` (demi)
|
||||
- Bug #9046: Fixed problem with endless error loop when an error occurred after sending a stream or file download response to the user (cebe)
|
||||
- Bug #9063: Workaround for MySQL losing table case when adding index (sebathi)
|
||||
- Bug #9127, #9128: Fixed MSSQL `QueryBuilder::renameColumn()` and `QueryBuilder::renameTable()` escaping (sitawit)
|
||||
- Bug #9161: Fixed `yii\web\Request` ignore `queryParams` when resolve request (zetamen)
|
||||
- Bug: Fixed string comparison in `BaseActiveRecord::unlink()` which may result in wrong comparison result for hash valued primary keys starting with `0e` (cebe)
|
||||
- Bug: Pass correct action name to `yii\console\Controller::options()` when default action was requested (cebe)
|
||||
- Bug: Automatic garbage collection in `yii\caching\FileCache` was not triggered (kidol)
|
||||
@ -43,6 +46,7 @@ Yii Framework 2 Change Log
|
||||
- Enh #8903: PostgreSQL `QueryBuilder::createIndex()` can now specify the index method to use (LAV45)
|
||||
- Enh #9011: Allow `yii\widgets\MaskedInput` to produce an input tag of a custom type (TriAnMan)
|
||||
- Enh #9038: Write warning to log in case `FileCache` fails to write into file (foccy)
|
||||
- Enh #9149: Print directory migrationPath in a `yii migrate` command error. (RusAlex)
|
||||
- Chg #6354: `ErrorHandler::logException()` will now log the whole exception object instead of only its string representation (cebe)
|
||||
- Chg #8556: Extracted `yii\web\User::getAuthManager()` method (samdark)
|
||||
|
||||
|
||||
@ -13,7 +13,7 @@ use yii\base\InvalidConfigException;
|
||||
/**
|
||||
* FileDependency represents a dependency based on a file's last modification time.
|
||||
*
|
||||
* If th last modification time of the file specified via [[fileName]] is changed,
|
||||
* If the last modification time of the file specified via [[fileName]] is changed,
|
||||
* the dependency is considered as changed.
|
||||
*
|
||||
* @author Qiang Xue <qiang.xue@gmail.com>
|
||||
|
||||
@ -75,7 +75,6 @@ class Application extends \yii\base\Application
|
||||
*/
|
||||
public $controller;
|
||||
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
|
||||
@ -68,7 +68,7 @@ abstract class BaseMigrateController extends Controller
|
||||
$path = Yii::getAlias($this->migrationPath);
|
||||
if (!is_dir($path)) {
|
||||
if ($action->id !== 'create') {
|
||||
throw new Exception('Migration failed. Directory specified in migrationPath doesn\'t exist.');
|
||||
throw new Exception("Migration failed. Directory specified in migrationPath doesn't exist: {$this->migrationPath}");
|
||||
}
|
||||
FileHelper::createDirectory($path);
|
||||
}
|
||||
@ -367,7 +367,7 @@ abstract class BaseMigrateController extends Controller
|
||||
* ~~~
|
||||
*
|
||||
* @param integer $limit the maximum number of migrations to be displayed.
|
||||
* If it is 0, the whole migration history will be displayed.
|
||||
* If it is "all", the whole migration history will be displayed.
|
||||
* @throws \yii\console\Exception if invalid limit value passed
|
||||
*/
|
||||
public function actionHistory($limit = 10)
|
||||
|
||||
@ -119,25 +119,28 @@ class QueryBuilder extends \yii\db\QueryBuilder
|
||||
|
||||
/**
|
||||
* Builds a SQL statement for renaming a DB table.
|
||||
* @param string $table the table to be renamed. The name will be properly quoted by the method.
|
||||
* @param string $oldName the table to be renamed. The name will be properly quoted by the method.
|
||||
* @param string $newName the new table name. The name will be properly quoted by the method.
|
||||
* @return string the SQL statement for renaming a DB table.
|
||||
*/
|
||||
public function renameTable($table, $newName)
|
||||
public function renameTable($oldName, $newName)
|
||||
{
|
||||
return "sp_rename '$table', '$newName'";
|
||||
return 'sp_rename ' . $this->db->quoteTableName($oldName) . ', ' . $this->db->quoteTableName($newName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a SQL statement for renaming a column.
|
||||
* @param string $table the table whose column is to be renamed. The name will be properly quoted by the method.
|
||||
* @param string $name the old name of the column. The name will be properly quoted by the method.
|
||||
* @param string $oldName the old name of the column. The name will be properly quoted by the method.
|
||||
* @param string $newName the new name of the column. The name will be properly quoted by the method.
|
||||
* @return string the SQL statement for renaming a DB column.
|
||||
*/
|
||||
public function renameColumn($table, $name, $newName)
|
||||
public function renameColumn($table, $oldName, $newName)
|
||||
{
|
||||
return "sp_rename '$table.$name', '$newName', 'COLUMN'";
|
||||
$table = $this->db->quoteTableName($table);
|
||||
$oldName = $this->db->quoteColumnName($oldName);
|
||||
$newName = $this->db->quoteColumnName($newName);
|
||||
return "sp_rename '{$table}.{$oldName}', {$newName}, 'COLUMN'";
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@ -80,6 +80,19 @@ class QueryBuilder extends \yii\db\QueryBuilder
|
||||
. $this->db->quoteColumnName($newName);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
* @see https://bugs.mysql.com/bug.php?id=48875
|
||||
*/
|
||||
public function createIndex($name, $table, $columns, $unique = false)
|
||||
{
|
||||
return 'ALTER TABLE '
|
||||
. $this->db->quoteTableName($table)
|
||||
. ($unique ? ' ADD UNIQUE INDEX ' : ' ADD INDEX ')
|
||||
. $this->db->quoteTableName($name)
|
||||
. ' (' . $this->buildColumns($columns) . ')';
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a SQL statement for dropping a foreign key constraint.
|
||||
* @param string $name the name of the foreign key constraint to be dropped. The name will be properly quoted by the method.
|
||||
|
||||
@ -98,5 +98,5 @@ return [
|
||||
'{nFormatted} {n, plural, =1{pebibyte} other{pebibytes}}' => '{nFormatted} بيبيبايت',
|
||||
'{nFormatted} {n, plural, =1{petabyte} other{petabytes}}' => '{nFormatted} بيتابايت',
|
||||
'{nFormatted} {n, plural, =1{tebibyte} other{tebibytes}}' => '{nFormatted} تيبيبايت',
|
||||
'{nFormatted} {n, plural, =1{terabyte} other{terabytes}}' => '{nFormatted} تيرابايت',
|
||||
'{nFormatted} {n, plural, =1{terabyte} other{terabytes}}' => '{nFormatted} تيرابايت',
|
||||
];
|
||||
|
||||
@ -50,7 +50,6 @@ class Application extends \yii\base\Application
|
||||
*/
|
||||
public $controller;
|
||||
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
|
||||
@ -180,9 +180,12 @@ class Request extends \yii\base\Request
|
||||
$result = Yii::$app->getUrlManager()->parseRequest($this);
|
||||
if ($result !== false) {
|
||||
list ($route, $params) = $result;
|
||||
$_GET = $params + $_GET; // preserve numeric keys
|
||||
|
||||
return [$route, $_GET];
|
||||
if ($this->_queryParams === null) {
|
||||
$_GET = $params + $_GET; // preserve numeric keys
|
||||
} else {
|
||||
$this->_queryParams = $params + $this->_queryParams;
|
||||
}
|
||||
return [$route, $this->getQueryParams()];
|
||||
} else {
|
||||
throw new NotFoundHttpException(Yii::t('yii', 'Page not found.'));
|
||||
}
|
||||
|
||||
@ -90,4 +90,60 @@ class RequestTest extends TestCase
|
||||
|
||||
$this->assertTrue($request->validateCsrfToken($token));
|
||||
}
|
||||
|
||||
public function testResolve()
|
||||
{
|
||||
$this->mockWebApplication([
|
||||
'components' => [
|
||||
'urlManager' => [
|
||||
'enablePrettyUrl' => true,
|
||||
'showScriptName' => false,
|
||||
'cache' => null,
|
||||
'rules' => [
|
||||
'posts' => 'post/list',
|
||||
'post/<id>' => 'post/view',
|
||||
],
|
||||
]
|
||||
]
|
||||
]);
|
||||
|
||||
$request = new Request();
|
||||
$request->pathInfo = 'posts';
|
||||
|
||||
$_GET['page'] = 1;
|
||||
$result = $request->resolve();
|
||||
$this->assertEquals(['post/list', ['page' => 1]], $result);
|
||||
$this->assertEquals($_GET, ['page' => 1]);
|
||||
|
||||
$request->setQueryParams(['page' => 5]);
|
||||
$result = $request->resolve();
|
||||
$this->assertEquals(['post/list', ['page' => 5]], $result);
|
||||
$this->assertEquals($_GET, ['page' => 1]);
|
||||
|
||||
$request->setQueryParams(['custom-page' => 5]);
|
||||
$result = $request->resolve();
|
||||
$this->assertEquals(['post/list', ['custom-page' => 5]], $result);
|
||||
$this->assertEquals($_GET, ['page' => 1]);
|
||||
|
||||
unset($_GET['page']);
|
||||
|
||||
$request = new Request();
|
||||
$request->pathInfo = 'post/21';
|
||||
|
||||
$this->assertEquals($_GET, []);
|
||||
$result = $request->resolve();
|
||||
$this->assertEquals(['post/view', ['id' => 21]], $result);
|
||||
$this->assertEquals($_GET, ['id' => 21]);
|
||||
|
||||
$_GET['id'] = 42;
|
||||
$result = $request->resolve();
|
||||
$this->assertEquals(['post/view', ['id' => 21]], $result);
|
||||
$this->assertEquals($_GET, ['id' => 21]);
|
||||
|
||||
$_GET['id'] = 63;
|
||||
$request->setQueryParams(['token' => 'secret']);
|
||||
$result = $request->resolve();
|
||||
$this->assertEquals(['post/view', ['id' => 21, 'token' => 'secret']], $result);
|
||||
$this->assertEquals($_GET, ['id' => 63]);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user