Commit 8bf91847 by Carsten Brandt

edited the guid. fixed a huge bunch of links, hopefully all :)

parent 3846e5c3
...@@ -506,8 +506,8 @@ $order->subtotal = 100; ...@@ -506,8 +506,8 @@ $order->subtotal = 100;
$customer->link('orders', $order); $customer->link('orders', $order);
``` ```
The [[yii\db\Activerecord::link()|link()]] call above will set the `customer_id` of the order to be the primary key The [[yii\db\ActiveRecord::link()|link()]] call above will set the `customer_id` of the order to be the primary key
value of `$customer` and then call [[yii\db\Activerecord::save()|save()]] to save the order into database. value of `$customer` and then call [[yii\db\ActiveRecord::save()|save()]] to save the order into database.
Life Cycles of an ActiveRecord Object Life Cycles of an ActiveRecord Object
...@@ -520,33 +520,33 @@ method overriding and event handling mechanisms. ...@@ -520,33 +520,33 @@ method overriding and event handling mechanisms.
When instantiating a new ActiveRecord instance, we will have the following life cycles: When instantiating a new ActiveRecord instance, we will have the following life cycles:
1. constructor 1. constructor
2. [[yii\db\Activerecord::init()|init()]]: will trigger an [[yii\db\Activerecord::EVENT_INIT|EVENT_INIT]] event 2. [[yii\db\ActiveRecord::init()|init()]]: will trigger an [[yii\db\ActiveRecord::EVENT_INIT|EVENT_INIT]] event
When getting an ActiveRecord instance through the [[yii\db\Activerecord::find()|find()]] method, we will have the following life cycles: When getting an ActiveRecord instance through the [[yii\db\ActiveRecord::find()|find()]] method, we will have the following life cycles:
1. constructor 1. constructor
2. [[yii\db\Activerecord::init()|init()]]: will trigger an [[yii\db\Activerecord::EVENT_INIT|EVENT_INIT]] event 2. [[yii\db\ActiveRecord::init()|init()]]: will trigger an [[yii\db\ActiveRecord::EVENT_INIT|EVENT_INIT]] event
3. [[yii\db\Activerecord::afterFind()|afterFind()]]: will trigger an [[yii\db\Activerecord::EVENT_AFTER_FIND|EVENT_AFTER_FIND]] event 3. [[yii\db\ActiveRecord::afterFind()|afterFind()]]: will trigger an [[yii\db\ActiveRecord::EVENT_AFTER_FIND|EVENT_AFTER_FIND]] event
When calling [[yii\db\Activerecord::save()|save()]] to insert or update an ActiveRecord, we will have the following life cycles: When calling [[yii\db\ActiveRecord::save()|save()]] to insert or update an ActiveRecord, we will have the following life cycles:
1. [[yii\db\Activerecord::beforeValidate()|beforeValidate()]]: will trigger an [[yii\db\Activerecord::EVENT_BEFORE_VALIDATE|EVENT_BEFORE_VALIDATE]] event 1. [[yii\db\ActiveRecord::beforeValidate()|beforeValidate()]]: will trigger an [[yii\db\ActiveRecord::EVENT_BEFORE_VALIDATE|EVENT_BEFORE_VALIDATE]] event
2. [[yii\db\Activerecord::afterValidate()|afterValidate()]]: will trigger an [[yii\db\Activerecord::EVENT_AFTER_VALIDATE|EVENT_AFTER_VALIDATE]] event 2. [[yii\db\ActiveRecord::afterValidate()|afterValidate()]]: will trigger an [[yii\db\ActiveRecord::EVENT_AFTER_VALIDATE|EVENT_AFTER_VALIDATE]] event
3. [[yii\db\Activerecord::beforeSave()|beforeSave()]]: will trigger an [[yii\db\Activerecord::EVENT_BEFORE_INSERT|EVENT_BEFORE_INSERT]] or [[yii\db\Activerecord::EVENT_BEFORE_UPDATE|EVENT_BEFORE_UPDATE]] event 3. [[yii\db\ActiveRecord::beforeSave()|beforeSave()]]: will trigger an [[yii\db\ActiveRecord::EVENT_BEFORE_INSERT|EVENT_BEFORE_INSERT]] or [[yii\db\ActiveRecord::EVENT_BEFORE_UPDATE|EVENT_BEFORE_UPDATE]] event
4. perform the actual data insertion or updating 4. perform the actual data insertion or updating
5. [[yii\db\Activerecord::afterSave()|afterSave()]]: will trigger an [[yii\db\Activerecord::EVENT_AFTER_INSERT|EVENT_AFTER_INSERT]] or [[yii\db\Activerecord::EVENT_AFTER_UPDATE|EVENT_AFTER_UPDATE]] event 5. [[yii\db\ActiveRecord::afterSave()|afterSave()]]: will trigger an [[yii\db\ActiveRecord::EVENT_AFTER_INSERT|EVENT_AFTER_INSERT]] or [[yii\db\ActiveRecord::EVENT_AFTER_UPDATE|EVENT_AFTER_UPDATE]] event
Finally when calling [[yii\db\Activerecord::delete()|delete()]] to delete an ActiveRecord, we will have the following life cycles: Finally when calling [[yii\db\ActiveRecord::delete()|delete()]] to delete an ActiveRecord, we will have the following life cycles:
1. [[yii\db\Activerecord::beforeDelete()|beforeDelete()]]: will trigger an [[yii\db\Activerecord::EVENT_BEFORE_DELETE|EVENT_BEFORE_DELETE]] event 1. [[yii\db\ActiveRecord::beforeDelete()|beforeDelete()]]: will trigger an [[yii\db\ActiveRecord::EVENT_BEFORE_DELETE|EVENT_BEFORE_DELETE]] event
2. perform the actual data deletion 2. perform the actual data deletion
3. [[yii\db\Activerecord::afterDelete()|afterDelete()]]: will trigger an [[yii\db\Activerecord::EVENT_AFTER_DELETE|EVENT_AFTER_DELETE]] event 3. [[yii\db\ActiveRecord::afterDelete()|afterDelete()]]: will trigger an [[yii\db\ActiveRecord::EVENT_AFTER_DELETE|EVENT_AFTER_DELETE]] event
Custom scopes Custom scopes
------------- -------------
When [[yii\db\Activerecord::find()|find()]] or [[yii\db\Activerecord::findBySql()|findBySql()]] Active Record method is being called without parameters it returns an [[yii\db\Activerecord::yii\db\ActiveQuery|yii\db\ActiveQuery]] When [[yii\db\ActiveRecord::find()|find()]] or [[yii\db\ActiveRecord::findBySql()|findBySql()]] Active Record method is being called without parameters it returns an [[yii\db\ActiveRecord::yii\db\ActiveQuery|yii\db\ActiveQuery]]
instance. This object holds all the parameters and conditions for a future query and also allows you to customize these instance. This object holds all the parameters and conditions for a future query and also allows you to customize these
using a set of methods that are called scopes. By default there is a good set of such methods some of which we've using a set of methods that are called scopes. By default there is a good set of such methods some of which we've
already used above: `where`, `orderBy`, `limit` etc. already used above: `where`, `orderBy`, `limit` etc.
...@@ -657,8 +657,8 @@ When a few DB operations are related and are executed ...@@ -657,8 +657,8 @@ When a few DB operations are related and are executed
TODO: FIXME: WIP, TBD, https://github.com/yiisoft/yii2/issues/226 TODO: FIXME: WIP, TBD, https://github.com/yiisoft/yii2/issues/226
, ,
[[yii\db\Activerecord::afterSave()|afterSave()]], [[yii\db\Activerecord::beforeDelete()|beforeDelete()]] and/or [[yii\db\Activerecord::afterDelete()|afterDelete()]] life cycle methods. Developer may come [[yii\db\ActiveRecord::afterSave()|afterSave()]], [[yii\db\ActiveRecord::beforeDelete()|beforeDelete()]] and/or [[yii\db\ActiveRecord::afterDelete()|afterDelete()]] life cycle methods. Developer may come
to the solution of overriding ActiveRecord [[yii\db\Activerecord::save()|save()]] method with database transaction wrapping or to the solution of overriding ActiveRecord [[yii\db\ActiveRecord::save()|save()]] method with database transaction wrapping or
even using transaction in controller action, which is strictly speaking doesn't seem to be a good even using transaction in controller action, which is strictly speaking doesn't seem to be a good
practice (recall "skinny-controller / fat-model" fundamental rule). practice (recall "skinny-controller / fat-model" fundamental rule).
...@@ -686,7 +686,7 @@ class Product extends \yii\db\ActiveRecord ...@@ -686,7 +686,7 @@ class Product extends \yii\db\ActiveRecord
} }
``` ```
Overriding [[yii\db\Activerecord::save()|save()]] method: Overriding [[yii\db\ActiveRecord::save()|save()]] method:
```php ```php
......
...@@ -2,9 +2,9 @@ Managing assets ...@@ -2,9 +2,9 @@ Managing assets
=============== ===============
An asset in Yii is a file that is included into the page. It could be CSS, JavaScript or An asset in Yii is a file that is included into the page. It could be CSS, JavaScript or
any other file. Framework provides many ways to work with assets from basics such as adding `<script src="` tag any other file. Framework provides many ways to work with assets from basics such as adding `<script src="...">` tag
for a file that is [handled by View](view.md) section to advanced usage such as publishing files that are not for a file that is [handled by View](view.md) section to advanced usage such as publishing files that are not
under webserve document root, resolving JavaScript dependencies or minifying CSS. under the webservers document root, resolving JavaScript dependencies or minifying CSS.
Declaring asset bundle Declaring asset bundle
---------------------- ----------------------
...@@ -13,9 +13,15 @@ In order to publish some assets you should declare an asset bundle first. The bu ...@@ -13,9 +13,15 @@ In order to publish some assets you should declare an asset bundle first. The bu
directories to be published and their dependencies on other asset bundles. directories to be published and their dependencies on other asset bundles.
Both basic and advanced application templates contain `AppAsset` asset bundle class that defines assets required Both basic and advanced application templates contain `AppAsset` asset bundle class that defines assets required
application wide. Let's review basic application asset bundle class: application wide. An asset bundle class always extends from [[yii\web\AssetBundle]].
Let's review basic application's asset bundle class:
```php ```php
<?php
use yii\web\AssetBundle as AssetBundle;
class AppAsset extends AssetBundle class AppAsset extends AssetBundle
{ {
public $basePath = '@webroot'; public $basePath = '@webroot';
......
...@@ -209,7 +209,7 @@ public function behaviors() ...@@ -209,7 +209,7 @@ public function behaviors()
} }
``` ```
Another way is to call [[User::checkAccess()]] where appropriate. Another way is to call [[yii\web\User::checkAccess()]] where appropriate.
### Using DB-based storage for RBAC ### Using DB-based storage for RBAC
......
...@@ -5,21 +5,22 @@ Basic concepts of Yii ...@@ -5,21 +5,22 @@ Basic concepts of Yii
Component and Object Component and Object
-------------------- --------------------
Classes of the Yii framework usually extend from one of the two base classes [[Object]] and [[Component]]. Classes of the Yii framework usually extend from one of the two base classes [[yii\base\Object]] and [[yii\base\Component]].
These classes provide useful features that are added automatically to all classes extending from them. These classes provide useful features that are added automatically to all classes extending from them.
The `Object` class provides the [configuration and property feature](../api/base/Object.md). The [[yii\base\Object|Object]] class provides the [configuration and property feature](../api/base/Object.md).
The `Component` class extends from `Object` and adds [event handling](events.md) and [behaviors](behaviors.md). The [[yii\base\Component|Component]] class extends from [[yii\base\Object|Object]] and adds
[event handling](events.md) and [behaviors](behaviors.md).
`Object` is usually used for classes that represent basic data structures while `Component` is used for [[yii\base\Object|Object]] is usually used for classes that represent basic data structures while
application components and other classes that implement higher logic. [[yii\base\Component|Component]] is used for application components and other classes that implement higher logic.
Object Configuration Object Configuration
-------------------- --------------------
The [[Object]] class introduces a uniform way of configuring objects. Any descendant class The [[yii\base\Object|Object]] class introduces a uniform way of configuring objects. Any descendant class
of [[Object]] should declare its constructor (if needed) in the following way so that of [[yii\base\Object|Object]] should declare its constructor (if needed) in the following way so that
it can be properly configured: it can be properly configured:
```php ```php
......
...@@ -9,8 +9,10 @@ code execution. Unlike [PHP's traits](http://www.php.net/traits), behaviors can ...@@ -9,8 +9,10 @@ code execution. Unlike [PHP's traits](http://www.php.net/traits), behaviors can
Using behaviors Using behaviors
--------------- ---------------
A behavior can be attached to any class that extends from `Component`. In order to attach a behavior to a class, the component class must implement the `behaviors` A behavior can be attached to any class that extends from [[yii\base\Component]]. In order to attach a behavior to a class,
method. As an example, Yii provides the `AutoTimestamp` behavior for automatically updating timestamp fields when saving an Active Record model: the component class must implement the `behaviors`
method. As an example, Yii provides the [[yii\behaviors\AutoTimestamp|AutoTimestamp]] behavior for automatically updating timestamp
fields when saving an [[yii\db\ActiveRecord|Active Record]] model:
```php ```php
class User extends ActiveRecord class User extends ActiveRecord
...@@ -32,7 +34,10 @@ class User extends ActiveRecord ...@@ -32,7 +34,10 @@ class User extends ActiveRecord
} }
``` ```
In the above, the `class` value is a string representing the fully qualified behavior class name. All of the other key-value pairs represent corresponding public properties of the `AutoTimestamp` class, thereby customizing how the behavior functions. In the above, the `class` value is a string representing the fully qualified behavior class name.
All of the other key-value pairs represent corresponding public properties of the [[yii\behaviors\AutoTimestamp|AutoTimestamp]]
class, thereby customizing how the behavior functions.
Creating your own behaviors Creating your own behaviors
--------------------------- ---------------------------
......
...@@ -33,18 +33,18 @@ Yii widgets ...@@ -33,18 +33,18 @@ Yii widgets
Most complex bootstrap components are wrapped into Yii widgets to allow more robust syntax and integrate with Most complex bootstrap components are wrapped into Yii widgets to allow more robust syntax and integrate with
framework features. All widgets belong to `\yii\bootstrap` namespace: framework features. All widgets belong to `\yii\bootstrap` namespace:
- Alert - [[yii\bootstrap\Alert|Alert]]
- Button - [[yii\bootstrap\Button|Button]]
- ButtonDropdown - [[yii\bootstrap\ButtonDropdown|ButtonDropdown]]
- ButtonGroup - [[yii\bootstrap\ButtonGroup|ButtonGroup]]
- Carousel - [[yii\bootstrap\Carousel|Carousel]]
- Collapse - [[yii\bootstrap\Collapse|Collapse]]
- Dropdown - [[yii\bootstrap\Dropdown|Dropdown]]
- Modal - [[yii\bootstrap\Modal|Modal]]
- Nav - [[yii\bootstrap\Nav|Nav]]
- NavBar - [[yii\bootstrap\NavBar|NavBar]]
- Progress - [[yii\bootstrap\Progress|Progress]]
- Tabs - [[yii\bootstrap\Tabs|Tabs]]
Using the .less files of Bootstrap directly Using the .less files of Bootstrap directly
...@@ -52,7 +52,7 @@ Using the .less files of Bootstrap directly ...@@ -52,7 +52,7 @@ Using the .less files of Bootstrap directly
If you want to include the [Bootstrap css directly in your less files](http://getbootstrap.com/getting-started/#customizing) If you want to include the [Bootstrap css directly in your less files](http://getbootstrap.com/getting-started/#customizing)
you may need to disable the original bootstrap css files to be loaded. you may need to disable the original bootstrap css files to be loaded.
You can do this by setting the css property of the `BootstrapAsset` to be empty. You can do this by setting the css property of the [[yii\bootstrap\BootstrapAsset|BootstrapAsset]] to be empty.
For this you need to configure the `assetManagner` application component as follows: For this you need to configure the `assetManagner` application component as follows:
```php ```php
......
...@@ -73,7 +73,7 @@ is a summary of the available cache components: ...@@ -73,7 +73,7 @@ is a summary of the available cache components:
[Zend Data Cache](http://files.zend.com/help/Zend-Server-6/zend-server.htm#data_cache_component.htm) [Zend Data Cache](http://files.zend.com/help/Zend-Server-6/zend-server.htm#data_cache_component.htm)
as the underlying caching medium. as the underlying caching medium.
Tip: because all these cache components extend from the same base class [[Cache]], one can switch to use Tip: because all these cache components extend from the same base class [[yii\caching\Cache]], one can switch to use
a different type of cache without modifying the code that uses cache. a different type of cache without modifying the code that uses cache.
Caching can be used at different levels. At the lowest level, we use cache to store a single piece of data, Caching can be used at different levels. At the lowest level, we use cache to store a single piece of data,
...@@ -92,9 +92,9 @@ Data Caching ...@@ -92,9 +92,9 @@ Data Caching
Data caching is about storing some PHP variable in cache and retrieving it later from cache. For this purpose, Data caching is about storing some PHP variable in cache and retrieving it later from cache. For this purpose,
the cache component base class [[\yii\caching\Cache]] provides two methods that are used most of the time: the cache component base class [[\yii\caching\Cache]] provides two methods that are used most of the time:
[[set()]] and [[get()]]. Note, only serializable variables and objects could be cached successfully. [[yii\caching\Cache::set()|set()]] and [[yii\caching\Cache::get()|get()]]. Note, only serializable variables and objects could be cached successfully.
To store a variable `$value` in cache, we choose a unique `$key` and call [[set()]] to store it: To store a variable `$value` in cache, we choose a unique `$key` and call [[yii\caching\Cache::set()|set()]] to store it:
```php ```php
Yii::$app->cache->set($key, $value); Yii::$app->cache->set($key, $value);
...@@ -102,7 +102,7 @@ Yii::$app->cache->set($key, $value); ...@@ -102,7 +102,7 @@ Yii::$app->cache->set($key, $value);
The cached data will remain in the cache forever unless it is removed because of some caching policy The cached data will remain in the cache forever unless it is removed because of some caching policy
(e.g. caching space is full and the oldest data are removed). To change this behavior, we can also supply (e.g. caching space is full and the oldest data are removed). To change this behavior, we can also supply
an expiration parameter when calling [[set()]] so that the data will be removed from the cache after an expiration parameter when calling [[yii\caching\Cache::set()|set()]] so that the data will be removed from the cache after
a certain period of time: a certain period of time:
```php ```php
...@@ -110,7 +110,7 @@ a certain period of time: ...@@ -110,7 +110,7 @@ a certain period of time:
Yii::$app->cache->set($key, $value, 45); Yii::$app->cache->set($key, $value, 45);
``` ```
Later when we need to access this variable (in either the same or a different web request), we call [[get()]] Later when we need to access this variable (in either the same or a different web request), we call [[yii\caching\Cache::get()|get()]]
with the key to retrieve it from cache. If the value returned is `false`, it means the value is not available with the key to retrieve it from cache. If the value returned is `false`, it means the value is not available
in cache and we should regenerate it: in cache and we should regenerate it:
...@@ -134,18 +134,20 @@ may be cached in the application. It is **NOT** required that the key is unique ...@@ -134,18 +134,20 @@ may be cached in the application. It is **NOT** required that the key is unique
the cache component is intelligent enough to differentiate keys for different applications. the cache component is intelligent enough to differentiate keys for different applications.
Some cache storages, such as MemCache, APC, support retrieving multiple cached values in a batch mode, Some cache storages, such as MemCache, APC, support retrieving multiple cached values in a batch mode,
which may reduce the overhead involved in retrieving cached data. A method named [[mget()]] is provided which may reduce the overhead involved in retrieving cached data. A method named [[yii\caching\Cache::mget()|mget()]] is provided
to exploit this feature. In case the underlying cache storage does not support this feature, to exploit this feature. In case the underlying cache storage does not support this feature,
[[mget()]] will still simulate it. [[yii\caching\Cache::mget()|mget()]] will still simulate it.
To remove a cached value from cache, call [[delete()]]; and to remove everything from cache, call [[flush()]]. To remove a cached value from cache, call [[yii\caching\Cache::delete()|delete()]]; and to remove everything from cache, call
Be very careful when calling [[flush()]] because it also removes cached data that are from other applications. [[yii\caching\Cache::flush()|flush()]].
Be very careful when calling [[yii\caching\Cache::flush()|flush()]] because it also removes cached data that are from
other applications if the cache is shared among different applications.
Note, because [[Cache]] implements `ArrayAccess`, a cache component can be used liked an array. The followings Note, because [[yii\caching\Cache]] implements `ArrayAccess`, a cache component can be used liked an array. The followings
are some examples: are some examples:
```php ```php
$cache = Yii::$app->getComponent('cache'); $cache = Yii::$app->cache;
$cache['var1'] = $value1; // equivalent to: $cache->set('var1', $value1); $cache['var1'] = $value1; // equivalent to: $cache->set('var1', $value1);
$value2 = $cache['var2']; // equivalent to: $value2 = $cache->get('var2'); $value2 = $cache['var2']; // equivalent to: $value2 = $cache->get('var2');
``` ```
...@@ -157,10 +159,10 @@ are caching the content of some file and the file is changed, we should invalida ...@@ -157,10 +159,10 @@ are caching the content of some file and the file is changed, we should invalida
content from the file instead of the cache. content from the file instead of the cache.
We represent a dependency as an instance of [[\yii\caching\Dependency]] or its child class. We pass the dependency We represent a dependency as an instance of [[\yii\caching\Dependency]] or its child class. We pass the dependency
instance along with the data to be cached when calling `set()`. instance along with the data to be cached when calling [[yii\caching\Cache::set()|set()]].
```php ```php
use yii\cache\FileDependency; use yii\caching\FileDependency;
// the value will expire in 30 seconds // the value will expire in 30 seconds
// it may also be invalidated earlier if the dependent file is changed // it may also be invalidated earlier if the dependent file is changed
...@@ -172,12 +174,12 @@ get a false value, indicating the data needs to be regenerated. ...@@ -172,12 +174,12 @@ get a false value, indicating the data needs to be regenerated.
Below is a summary of the available cache dependencies: Below is a summary of the available cache dependencies:
- [[\yii\cache\FileDependency]]: the dependency is changed if the file's last modification time is changed. - [[\yii\caching\FileDependency]]: the dependency is changed if the file's last modification time is changed.
- [[\yii\cache\GroupDependency]]: marks a cached data item with a group name. You may invalidate the cached data items - [[\yii\caching\GroupDependency]]: marks a cached data item with a group name. You may invalidate the cached data items
with the same group name all at once by calling [[\yii\cache\GroupDependency::invalidate()]]. with the same group name all at once by calling [[\yii\caching\GroupDependency::invalidate()]].
- [[\yii\cache\DbDependency]]: the dependency is changed if the query result of the specified SQL statement is changed. - [[\yii\caching\DbDependency]]: the dependency is changed if the query result of the specified SQL statement is changed.
- [[\yii\cache\ChainedDependency]]: the dependency is changed if any of the dependencies on the chain is changed. - [[\yii\caching\ChainedDependency]]: the dependency is changed if any of the dependencies on the chain is changed.
- [[\yii\cache\ExpressionDependency]]: the dependency is changed if the result of the specified PHP expression is - [[\yii\caching\ExpressionDependency]]: the dependency is changed if the result of the specified PHP expression is
changed. changed.
### Query Caching ### Query Caching
......
...@@ -103,7 +103,7 @@ by Yii with the corresponding types depended on your database management system. ...@@ -103,7 +103,7 @@ by Yii with the corresponding types depended on your database management system.
You can use them to write database independent migrations. You can use them to write database independent migrations.
For example `pk` will be replaced by `int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY` For example `pk` will be replaced by `int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY`
for MySQL and `integer PRIMARY KEY AUTOINCREMENT NOT NULL` for sqlite. for MySQL and `integer PRIMARY KEY AUTOINCREMENT NOT NULL` for sqlite.
See documentation of [[QueryBuilder::getColumnType()]] for more details and a list See documentation of [[yii\db\QueryBuilder::getColumnType()]] for more details and a list
of available types. You may also use the constants defined in [[\yii\db\Schema]] to of available types. You may also use the constants defined in [[\yii\db\Schema]] to
define column types. define column types.
......
...@@ -13,8 +13,9 @@ You can execute controller action using the following syntax: ...@@ -13,8 +13,9 @@ You can execute controller action using the following syntax:
yii <route> [--option1=value1 --option2=value2 ... argument1 argument2 ...] yii <route> [--option1=value1 --option2=value2 ... argument1 argument2 ...]
``` ```
For example, `MigrationController::actionCreate()` with `MigrationController::$migrationTable` set can be called from command For example, [[yii\console\controllers\MigrateController::actionCreate()|MigrateController::actionCreate()]]
line like the following: with [[yii\console\controllers\MigrateController::$migrationTable|MigrateController::$migrationTable]] set can
be called from command line like the following:
``` ```
yii migrate/create --migrationTable=my_migration yii migrate/create --migrationTable=my_migration
...@@ -79,7 +80,8 @@ you define one or several actions that correspond to the sub-commands of the com ...@@ -79,7 +80,8 @@ you define one or several actions that correspond to the sub-commands of the com
to implement certain tasks for that particular sub-command. to implement certain tasks for that particular sub-command.
When running a command, you need to specify the route to the corresponding controller action. For example, When running a command, you need to specify the route to the corresponding controller action. For example,
the route `migrate/create` specifies the sub-command corresponding to the `MigrateController::actionCreate()` action method. the route `migrate/create` specifies the sub-command corresponding to the
[[yii\console\controllers\MigrateController::actionCreate()|MigrateController::actionCreate()]] action method.
If a route does not contain an action ID, the default action will be executed. If a route does not contain an action ID, the default action will be executed.
### Options ### Options
......
...@@ -221,7 +221,7 @@ Action Filters ...@@ -221,7 +221,7 @@ Action Filters
Action filters are implemented via behaviors. You should extend from `ActionFilter` to Action filters are implemented via behaviors. You should extend from `ActionFilter` to
define a new filter. To use a filter, you should attach the filter class to the controller define a new filter. To use a filter, you should attach the filter class to the controller
as a behavior. For example, to use the [[AccessControl]] filter, you should have the following as a behavior. For example, to use the [[yii\web\AccessControl]] filter, you should have the following
code in a controller: code in a controller:
```php ```php
...@@ -238,8 +238,8 @@ public function behaviors() ...@@ -238,8 +238,8 @@ public function behaviors()
} }
``` ```
In order to learn more about access control check [authorization](authorization.md) section of the guide. In order to learn more about access control check the [authorization](authorization.md) section of the guide.
Two other filters, [[PageCache]] and [[HttpCache]] are described in [caching](caching.md) section of the guide. Two other filters, [[yii\web\PageCache]] and [[yii\web\HttpCache]] are described in the [caching](caching.md) section of the guide.
Catching all incoming requests Catching all incoming requests
------------------------------ ------------------------------
......
...@@ -78,14 +78,16 @@ use yii\widgets\ActiveForm; ...@@ -78,14 +78,16 @@ use yii\widgets\ActiveForm;
<?php ActiveForm::end() ?> <?php ActiveForm::end() ?>
``` ```
In the above code, `ActiveForm::begin()` not only creates a form instance, but also marks the beginning of the form. In the above code, [[yii\widgets\ActiveForm::begin()|ActiveForm::begin()]] not only creates a form instance, but also marks the beginning of the form.
All of the content placed between `ActiveForm::begin()` and `ActiveForm::end()` will be wrapped within the `<form>` tag. All of the content placed between [[yii\widgets\ActiveForm::begin()|ActiveForm::begin()]] and
[[yii\widgets\ActiveForm::end()|ActiveForm::end()]] will be wrapped within the `<form>` tag.
As with any widget, you can specify some options as to how the widget should be configured by passing an array to As with any widget, you can specify some options as to how the widget should be configured by passing an array to
the `begin` method. In this case, an extra CSS class and identifying ID are passed to be used in the opening `<form>` tag. the `begin` method. In this case, an extra CSS class and identifying ID are passed to be used in the opening `<form>` tag.
In order to create a form element in the form, along with the element's label, and any application JavaScript validation, In order to create a form element in the form, along with the element's label, and any application JavaScript validation,
the `field` method of the Active Form widget is called. When the invocation of this method is echoed directly, the result the [[yii\widgets\ActiveForm::field()|ActiveForm::field()]] method of the Active Form widget is called.
is a regular (text) input. To customize the output, you can chain additional methods to this call: When the invocation of this method is echoed directly, the result is a regular (text) input.
To customize the output, you can chain additional methods to this call:
```php ```php
<?= $form->field($model, 'password')->passwordInput() ?> <?= $form->field($model, 'password')->passwordInput() ?>
......
The Definitive Guide to Yii 2.0
===============================
This tutorial is released under the [Terms of Yii Documentation](http://www.yiiframework.com/doc/terms/).
All Rights Reserved.
2014 (c) Yii Software LLC.
Introduction Introduction
============ ------------
- [Overview](overview.md) - What is Yii and what is it good for? - [Overview](overview.md) - What is Yii and what is it good for?
Getting started Getting started
=============== ---------------
- [Upgrading from 1.1 to 2.0](upgrade-from-v1.md) - [Upgrading from 1.1 to 2.0](upgrade-from-v1.md)
- [Installation](installation.md) - How to download Yii and configure the Webserver? - [Installation](installation.md) - How to download Yii and configure the Webserver?
...@@ -16,7 +26,7 @@ Getting started ...@@ -16,7 +26,7 @@ Getting started
- [Creating your own Application structure](apps-own.md) - Learn how to start from scratch. - [Creating your own Application structure](apps-own.md) - Learn how to start from scratch.
Base concepts Base concepts
============= -------------
- [Basic concepts of Yii](basics.md) - The Object and Component class, Path aliases and autoloading - [Basic concepts of Yii](basics.md) - The Object and Component class, Path aliases and autoloading
- [MVC](mvc.md) - Implementation of MVC in Yii and a typical MVC application flow - [MVC](mvc.md) - Implementation of MVC in Yii and a typical MVC application flow
...@@ -27,7 +37,7 @@ Base concepts ...@@ -27,7 +37,7 @@ Base concepts
- [Behaviors](behaviors.md) - [Behaviors](behaviors.md)
Database Database
======== --------
- [Basics](database-basics.md) - Connecting to a database, basic queries, transactions and schema manipulation - [Basics](database-basics.md) - Connecting to a database, basic queries, transactions and schema manipulation
- [Query Builder](query-builder.md) - Querying the database using a simple abstraction layer - [Query Builder](query-builder.md) - Querying the database using a simple abstraction layer
...@@ -35,7 +45,7 @@ Database ...@@ -35,7 +45,7 @@ Database
- [Database Migration](console-migrate.md) - Versioning your database with database migrations - [Database Migration](console-migrate.md) - Versioning your database with database migrations
Developers Toolbox Developers Toolbox
================== ------------------
- [Automatic Code Generation](gii.md) - [Automatic Code Generation](gii.md)
- [Debug toolbar and debugger](module-debug.md) - [Debug toolbar and debugger](module-debug.md)
...@@ -43,7 +53,7 @@ Developers Toolbox ...@@ -43,7 +53,7 @@ Developers Toolbox
- [Logging](logging.md) - [Logging](logging.md)
Extensions and 3rd party libraries Extensions and 3rd party libraries
================================== ----------------------------------
- [Composer](composer.md) - How to manage applications dependencies via composer - [Composer](composer.md) - How to manage applications dependencies via composer
- [Extending Yii](extensions.md) - [Extending Yii](extensions.md)
...@@ -51,7 +61,7 @@ Extensions and 3rd party libraries ...@@ -51,7 +61,7 @@ Extensions and 3rd party libraries
- [Using Yii together with 3rd-Party Systems](using-3rd-party-libraries.md) - Using Yii in 3rd-Party Systems and using Yii 1 and 2 together - [Using Yii together with 3rd-Party Systems](using-3rd-party-libraries.md) - Using Yii in 3rd-Party Systems and using Yii 1 and 2 together
Security and access control Security and access control
=========================== ---------------------------
- [Authentication](authentication.md) - Identifying Users - [Authentication](authentication.md) - Identifying Users
- [Authorization](authorization.md) - Access control and RBAC - [Authorization](authorization.md) - Access control and RBAC
...@@ -59,7 +69,7 @@ Security and access control ...@@ -59,7 +69,7 @@ Security and access control
- [Views security](view.md#security) - how to prevent XSS - [Views security](view.md#security) - how to prevent XSS
Data providers, lists and grids Data providers, lists and grids
=============================== -------------------------------
- Overview - Overview
- Data providers - Data providers
...@@ -67,7 +77,7 @@ Data providers, lists and grids ...@@ -67,7 +77,7 @@ Data providers, lists and grids
- Lists - Lists
Advanced Topics Advanced Topics
=============== ---------------
- [Asset Management](assets.md) - [Asset Management](assets.md)
- [Working with forms](form.md) - [Working with forms](form.md)
...@@ -81,7 +91,7 @@ Advanced Topics ...@@ -81,7 +91,7 @@ Advanced Topics
- [Testing](testing.md) - [Testing](testing.md)
References References
========== ----------
- [Model validation reference](validation.md) - [Model validation reference](validation.md)
- [Official Composer documentation](http://getcomposer.org) - [Official Composer documentation](http://getcomposer.org)
...@@ -23,16 +23,16 @@ default. ...@@ -23,16 +23,16 @@ default.
There are multiple severity levels and corresponding methods available: There are multiple severity levels and corresponding methods available:
- `\Yii::trace` used maily for development purpose to indicate workflow of some code. Note that it only works in - [[Yii::trace]] used maily for development purpose to indicate workflow of some code. Note that it only works in
development mode when `YII_DEBUG` is set to `true`. development mode when `YII_DEBUG` is set to `true`.
- `\Yii::error` used when there's unrecoverable error. - [[Yii::error]] used when there's unrecoverable error.
- `\Yii::warning` used when an error occured but execution can be continued. - [[Yii::warning]] used when an error occured but execution can be continued.
- `\Yii::info` used to keep record of important events such as administrator logins. - [[Yii::info]] used to keep record of important events such as administrator logins.
Log targets Log targets
----------- -----------
When one of the logging methods is called, message is passed to `\yii\log\Logger` component also accessible as When one of the logging methods is called, message is passed to [[yii\log\Logger]] component also accessible as
`Yii::$app->log`. Logger accumulates messages in memory and then when there are enough messages or when current `Yii::$app->log`. Logger accumulates messages in memory and then when there are enough messages or when current
request finishes, sends them to different log targets, such as file or email. request finishes, sends them to different log targets, such as file or email.
...@@ -72,13 +72,15 @@ Each log target can have a name and can be referenced via the [[targets]] proper ...@@ -72,13 +72,15 @@ Each log target can have a name and can be referenced via the [[targets]] proper
Yii::$app->log->targets['file']->enabled = false; Yii::$app->log->targets['file']->enabled = false;
``` ```
When the application ends or [[flushInterval]] is reached, Logger will call [[flush()]] to send logged messages to When the application ends or [[yii\log\Logger::flushInterval|flushInterval]] is reached, Logger will call
different log targets, such as file, email, Web. [[yii\log\Logger::flush()|flush()]] to send logged messages to different log targets, such as file, email, web.
Configuring context information Configuring context information
------------------------------- -------------------------------
TDB
Profiling Profiling
--------- ---------
......
...@@ -28,7 +28,7 @@ The following diagram shows a typical workflow of a Yii application handling a ...@@ -28,7 +28,7 @@ The following diagram shows a typical workflow of a Yii application handling a
1. A user makes a request of the URL `http://www.example.com/index.php?r=post/show&id=1`. 1. A user makes a request of the URL `http://www.example.com/index.php?r=post/show&id=1`.
The Web server handles the request by executing the bootstrap script `index.php`. The Web server handles the request by executing the bootstrap script `index.php`.
2. The bootstrap script creates an [[Application|yii\web\Application]] instance and runs it. 2. The bootstrap script creates an [[yii\web\Application|Application]] instance and runs it.
3. The Application instance obtains the detailed user request information from an application component named `request`. 3. The Application instance obtains the detailed user request information from an application component named `request`.
4. The application determines which [controller](controller.md) and which action of that controller was requested. 4. The application determines which [controller](controller.md) and which action of that controller was requested.
This is accomplished with the help of an application component named `urlManager`. This is accomplished with the help of an application component named `urlManager`.
......
...@@ -158,7 +158,7 @@ Operator can be one of the following: ...@@ -158,7 +158,7 @@ Operator can be one of the following:
in the generated condition. in the generated condition.
- `or not like`: similar to the `not like` operator except that `OR` is used to concatenate - `or not like`: similar to the `not like` operator except that `OR` is used to concatenate
the `NOT LIKE` predicates. the `NOT LIKE` predicates.
- `exists`: requires one operand which must be an instance of [[Query]] representing the sub-query. - `exists`: requires one operand which must be an instance of [[yii\db\Query]] representing the sub-query.
It will build a `EXISTS (sub-query)` expression. It will build a `EXISTS (sub-query)` expression.
- `not exists`: similar to the `exists` operator and builds a `NOT EXISTS (sub-query)` expression. - `not exists`: similar to the `exists` operator and builds a `NOT EXISTS (sub-query)` expression.
......
...@@ -106,7 +106,7 @@ to achieve the same goal. ...@@ -106,7 +106,7 @@ to achieve the same goal.
In the following we will describe how to write a `UserProfile` unit test class using `yii2-codeception`. In the following we will describe how to write a `UserProfile` unit test class using `yii2-codeception`.
In your unit test class extending [[yii\codeception\DbTestCase]] or [[yii\codeception\TestCase]], In your unit test class extending [[yii\codeception\DbTestCase]] or [[yii\codeception\TestCase]],
declare which fixtures you want to use in the [[yii\testFixtureTrait::fixtures()|fixtures()]] method. For example, declare which fixtures you want to use in the [[yii\test\FixtureTrait::fixtures()|fixtures()]] method. For example,
```php ```php
namespace app\tests\unit\models; namespace app\tests\unit\models;
......
...@@ -20,9 +20,9 @@ class loader. ...@@ -20,9 +20,9 @@ class loader.
Component and Object Component and Object
-------------------- --------------------
Yii 2.0 breaks the `CComponent` class in 1.1 into two classes: `Object` and `Component`. Yii 2.0 breaks the `CComponent` class in 1.1 into two classes: [[yii\base\Object]] and [[yii\base\Component]].
The `Object` class is a lightweight base class that allows defining class properties The [[yii\base\Object|Object]] class is a lightweight base class that allows defining class properties
via getters and setters. The `Component` class extends from `Object` and supports via getters and setters. The [[yii\base\Component|Component]] class extends from [[yii\base\Object|Object]] and supports
the event feature and the behavior feature. the event feature and the behavior feature.
If your class does not need the event or behavior feature, you should consider using If your class does not need the event or behavior feature, you should consider using
...@@ -35,8 +35,8 @@ More details about Object and component can be found in the [Basic concepts sect ...@@ -35,8 +35,8 @@ More details about Object and component can be found in the [Basic concepts sect
Object Configuration Object Configuration
-------------------- --------------------
The `Object` class introduces a uniform way of configuring objects. Any descendant class The [[yii\base\Object|Object]] class introduces a uniform way of configuring objects. Any descendant class
of `Object` should declare its constructor (if needed) in the following way so that of [[yii\base\Object|Object]] should declare its constructor (if needed) in the following way so that
it can be properly configured: it can be properly configured:
```php ```php
...@@ -60,7 +60,7 @@ class MyClass extends \yii\base\Object ...@@ -60,7 +60,7 @@ class MyClass extends \yii\base\Object
In the above, the last parameter of the constructor must take a configuration array In the above, the last parameter of the constructor must take a configuration array
which contains name-value pairs for initializing the properties at the end of the constructor. which contains name-value pairs for initializing the properties at the end of the constructor.
You can override the `init()` method to do initialization work that should be done after You can override the [[yii\base\Object::init()|init()]] method to do initialization work that should be done after
the configuration is applied. the configuration is applied.
By following this convention, you will be able to create and configure a new object By following this convention, you will be able to create and configure a new object
...@@ -144,7 +144,7 @@ More on path aliases can be found in the [Basic concepts section](basics.md). ...@@ -144,7 +144,7 @@ More on path aliases can be found in the [Basic concepts section](basics.md).
View View
---- ----
Yii 2.0 introduces a `View` class to represent the view part of the MVC pattern. Yii 2.0 introduces a [[yii\web\View|View]] class to represent the view part of the MVC pattern.
It can be configured globally through the "view" application component. It is also It can be configured globally through the "view" application component. It is also
accessible in any view file via `$this`. This is one of the biggest changes compared to 1.1: accessible in any view file via `$this`. This is one of the biggest changes compared to 1.1:
**`$this` in a view file no longer refers to the controller or widget object.** **`$this` in a view file no longer refers to the controller or widget object.**
...@@ -162,15 +162,14 @@ $content = Yii::$app->view->renderFile($viewFile, $params); ...@@ -162,15 +162,14 @@ $content = Yii::$app->view->renderFile($viewFile, $params);
// $view->renderFile($viewFile, $params); // $view->renderFile($viewFile, $params);
``` ```
Also, there is no more `CClientScript` in Yii 2.0. The [[yii\web\View|View]] class has taken over its role
Also, there is no more `CClientScript` in Yii 2.0. The `View` class has taken over its role
with significant improvements. For more details, please see the "assets" subsection. with significant improvements. For more details, please see the "assets" subsection.
While Yii 2.0 continues to use PHP as its main template language, it comes with two official extensions While Yii 2.0 continues to use PHP as its main template language, it comes with two official extensions
adding support for two popular template engines: Smarty and Twig. The Prado template engine is adding support for two popular template engines: Smarty and Twig. The Prado template engine is
no longer supported. To use these template engines, you just need to use `tpl` as the file no longer supported. To use these template engines, you just need to use `tpl` as the file
extension for your Smarty views, or `twig` for Twig views. You may also configure the extension for your Smarty views, or `twig` for Twig views. You may also configure the
`View::renderers` property to use other template engines. See [Using template engines](template.md) section [[yii\web\View::$renderers|View::$renderers]] property to use other template engines. See [Using template engines](template.md) section
of the guide for more details. of the guide for more details.
See [View section](view.md) for more details. See [View section](view.md) for more details.
...@@ -179,12 +178,12 @@ See [View section](view.md) for more details. ...@@ -179,12 +178,12 @@ See [View section](view.md) for more details.
Models Models
------ ------
A model is now associated with a form name returned by its `formName()` method. This is A model is now associated with a form name returned by its [[yii\base\Model::formName()|formName()]] method. This is
mainly used when using HTML forms to collect user inputs for a model. Previously in 1.1, mainly used when using HTML forms to collect user inputs for a model. Previously in 1.1,
this is usually hardcoded as the class name of the model. this is usually hardcoded as the class name of the model.
New methods called `load()` and `Model::loadMultiple()` are introduced to simplify the data population from user inputs New methods called [[yii\base\Model::load()|load()] and [[yii\base\Model::loadMultiple()|Model::loadMultiple()]] are
to a model. For example, introduced to simplify the data population from user inputs to a model. For example,
```php ```php
$model = new Post; $model = new Post;
...@@ -204,10 +203,10 @@ while ($tagsCount-- > 0) { ...@@ -204,10 +203,10 @@ while ($tagsCount-- > 0) {
Model::loadMultiple($postTags, $_POST); Model::loadMultiple($postTags, $_POST);
``` ```
Yii 2.0 introduces a new method called `scenarios()` to declare which attributes require Yii 2.0 introduces a new method called [[yii\base\Model::scenarios()|scenarios()]] to declare which attributes require
validation under which scenario. Child classes should overwrite `scenarios()` to return validation under which scenario. Child classes should overwrite [[yii\base\Model::scenarios()|scenarios()]] to return
a list of scenarios and the corresponding attributes that need to be validated when a list of scenarios and the corresponding attributes that need to be validated when
`validate()` is called. For example, [[yii\base\Model::validate()|validate()]] is called. For example,
```php ```php
public function scenarios() public function scenarios()
...@@ -221,12 +220,12 @@ public function scenarios() ...@@ -221,12 +220,12 @@ public function scenarios()
This method also determines which attributes are safe and which are not. In particular, This method also determines which attributes are safe and which are not. In particular,
given a scenario, if an attribute appears in the corresponding attribute list in `scenarios()` given a scenario, if an attribute appears in the corresponding attribute list in [[yii\base\Model::scenarios()|scenarios()]]
and the name is not prefixed with `!`, it is considered *safe*. and the name is not prefixed with `!`, it is considered *safe*.
Because of the above change, Yii 2.0 no longer has "safe" and "unsafe" validators. Because of the above change, Yii 2.0 no longer has "safe" and "unsafe" validators.
If your model only has one scenario (very common), you do not have to overwrite `scenarios()`, If your model only has one scenario (very common), you do not have to overwrite [[yii\base\Model::scenarios()|scenarios()]],
and everything will still work like the 1.1 way. and everything will still work like the 1.1 way.
To learn more about Yii 2.0 models refer to [Models](model.md) section of the guide. To learn more about Yii 2.0 models refer to [Models](model.md) section of the guide.
...@@ -235,8 +234,9 @@ To learn more about Yii 2.0 models refer to [Models](model.md) section of the gu ...@@ -235,8 +234,9 @@ To learn more about Yii 2.0 models refer to [Models](model.md) section of the gu
Controllers Controllers
----------- -----------
The `render()` and `renderPartial()` methods now return the rendering results instead of directly The [[yii\base\Controller::render()|render()]] and [[yii\base\Controller::renderPartial()|renderPartial()]] methods
sending them out. You have to `echo` them explicitly, e.g., `echo $this->render(...);`. now return the rendering results instead of directly sending them out.
You have to `echo` them explicitly, e.g., `echo $this->render(...);`.
To learn more about Yii 2.0 controllers refer to [Controller](controller.md) section of the guide. To learn more about Yii 2.0 controllers refer to [Controller](controller.md) section of the guide.
...@@ -244,8 +244,11 @@ To learn more about Yii 2.0 controllers refer to [Controller](controller.md) sec ...@@ -244,8 +244,11 @@ To learn more about Yii 2.0 controllers refer to [Controller](controller.md) sec
Widgets Widgets
------- -------
Using a widget is more straightforward in 2.0. You mainly use the `begin()`, `end()` and `widget()` Using a widget is more straightforward in 2.0. You mainly use the
methods of the `Widget` class. For example, [[yii\base\Widget::begin()|begin()]],
[[yii\base\Widget::end()|end()]] and
[[yii\base\Widget::widget()|widget()]]
methods of the [[yii\base\Widget|Widget]] class. For example,
```php ```php
// Note that you have to "echo" the result to display it // Note that you have to "echo" the result to display it
...@@ -313,9 +316,9 @@ sources based on message categories. For more information, see the class documen ...@@ -313,9 +316,9 @@ sources based on message categories. For more information, see the class documen
Action Filters Action Filters
-------------- --------------
Action filters are implemented via behaviors now. You should extend from `ActionFilter` to Action filters are implemented via behaviors now. You should extend from [[yii\base\ActionFilter]] to
define a new filter. To use a filter, you should attach the filter class to the controller define a new filter. To use a filter, you should attach the filter class to the controller
as a behavior. For example, to use the `AccessControl` filter, you should have the following as a behavior. For example, to use the [[yii\web\AccessControl]] filter, you should have the following
code in a controller: code in a controller:
```php ```php
...@@ -342,8 +345,8 @@ Yii 2.0 introduces a new concept called *asset bundle*. It is similar to script ...@@ -342,8 +345,8 @@ Yii 2.0 introduces a new concept called *asset bundle*. It is similar to script
packages (managed by `CClientScript`) in 1.1, but with better support. packages (managed by `CClientScript`) in 1.1, but with better support.
An asset bundle is a collection of asset files (e.g. JavaScript files, CSS files, image files, etc.) An asset bundle is a collection of asset files (e.g. JavaScript files, CSS files, image files, etc.)
under a directory. Each asset bundle is represented as a class extending `AssetBundle`. under a directory. Each asset bundle is represented as a class extending [[yii\web\AssetBundle]].
By registering an asset bundle via `AssetBundle::register()`, you will be able to make By registering an asset bundle via [[yii\web\AssetBundle::register()]], you will be able to make
the assets in that bundle accessible via Web, and the current page will automatically the assets in that bundle accessible via Web, and the current page will automatically
contain the references to the JavaScript and CSS files specified in that bundle. contain the references to the JavaScript and CSS files specified in that bundle.
...@@ -352,18 +355,25 @@ To learn more about assets see the [asset manager documentation](assets.md). ...@@ -352,18 +355,25 @@ To learn more about assets see the [asset manager documentation](assets.md).
Static Helpers Static Helpers
-------------- --------------
Yii 2.0 introduces many commonly used static helper classes, such as `Html`, `ArrayHelper`, Yii 2.0 introduces many commonly used static helper classes, such as
`StringHelper`. These classes are designed to be easily extended. Note that static classes [[yii\helpers\Html|Html]],
[[yii\helpers\ArrayHelper|ArrayHelper]],
[[yii\helpers\StringHelper|StringHelper]].
[[yii\helpers\FileHelper|FileHelper]],
[[yii\helpers\Json|Json]],
[[yii\helpers\Security|Security]],
These classes are designed to be easily extended. Note that static classes
are usually hard to extend because of the fixed class name references. But Yii 2.0 are usually hard to extend because of the fixed class name references. But Yii 2.0
introduces the class map (via `Yii::$classMap`) to overcome this difficulty. introduces the class map (via [[Yii::$classMap]]) to overcome this difficulty.
`ActiveForm` ActiveForm
------------ ----------
Yii 2.0 introduces the *field* concept for building a form using `ActiveForm`. A field Yii 2.0 introduces the *field* concept for building a form using [[yii\widgets\ActiveForm]]. A field
is a container consisting of a label, an input, an error message, and/or a hint text. is a container consisting of a label, an input, an error message, and/or a hint text.
It is represented as an `ActiveField` object. Using fields, you can build a form more cleanly than before: It is represented as an [[yii\widgets\ActiveField|ActiveField]] object.
Using fields, you can build a form more cleanly than before:
```php ```php
<?php $form = yii\widgets\ActiveForm::begin(); ?> <?php $form = yii\widgets\ActiveForm::begin(); ?>
...@@ -376,13 +386,12 @@ It is represented as an `ActiveField` object. Using fields, you can build a form ...@@ -376,13 +386,12 @@ It is represented as an `ActiveField` object. Using fields, you can build a form
``` ```
Query Builder Query Builder
------------- -------------
In 1.1, query building is scattered among several classes, including `CDbCommand`, In 1.1, query building is scattered among several classes, including `CDbCommand`,
`CDbCriteria`, and `CDbCommandBuilder`. Yii 2.0 uses `Query` to represent a DB query `CDbCriteria`, and `CDbCommandBuilder`. Yii 2.0 uses [[yii\db\Query|Query]] to represent a DB query
and `QueryBuilder` to generate SQL statements from query objects. For example: and [[yii\db\QueryBuilder|QueryBuilder]] to generate SQL statements from query objects. For example:
```php ```php
$query = new \yii\db\Query; $query = new \yii\db\Query;
...@@ -395,18 +404,17 @@ $sql = $command->sql; ...@@ -395,18 +404,17 @@ $sql = $command->sql;
$rows = $command->queryAll(); $rows = $command->queryAll();
``` ```
Best of all, such query building methods can be used together with [[yii\db\ActiveRecord|ActiveRecord]],
Best of all, such query building methods can be used together with `ActiveRecord`,
as explained in the next sub-section. as explained in the next sub-section.
ActiveRecord ActiveRecord
------------ ------------
ActiveRecord has undergone significant changes in Yii 2.0. The most important one [[yii\db\ActiveRecord|ActiveRecord]] has undergone significant changes in Yii 2.0. The most important one
is the relational ActiveRecord query. In 1.1, you have to declare the relations is the relational ActiveRecord query. In 1.1, you have to declare the relations
in the `relations()` method. In 2.0, this is done via getter methods that return in the `relations()` method. In 2.0, this is done via getter methods that return
an `ActiveQuery` object. For example, the following method declares an "orders" relation: an [[yii\db\ActiveQuery|ActiveQuery]] object. For example, the following method declares an "orders" relation:
```php ```php
class Customer extends \yii\db\ActiveRecord class Customer extends \yii\db\ActiveRecord
...@@ -418,7 +426,6 @@ class Customer extends \yii\db\ActiveRecord ...@@ -418,7 +426,6 @@ class Customer extends \yii\db\ActiveRecord
} }
``` ```
You can use `$customer->orders` to access the customer's orders. You can also You can use `$customer->orders` to access the customer's orders. You can also
use `$customer->getOrders()->andWhere('status=1')->all()` to perform on-the-fly use `$customer->getOrders()->andWhere('status=1')->all()` to perform on-the-fly
relational query with customized query conditions. relational query with customized query conditions.
...@@ -431,7 +438,7 @@ by filtering with the primary keys of the primary records. ...@@ -431,7 +438,7 @@ by filtering with the primary keys of the primary records.
Yii 2.0 no longer uses the `model()` method when performing queries. Instead, you Yii 2.0 no longer uses the `model()` method when performing queries. Instead, you
use the `find()` method: use the [[yii\db\ActiveRecord::find()|find()]] method:
```php ```php
// to retrieve all *active* customers and order them by their ID: // to retrieve all *active* customers and order them by their ID:
...@@ -444,10 +451,10 @@ $customer = Customer::find(1); ...@@ -444,10 +451,10 @@ $customer = Customer::find(1);
``` ```
The `find()` method returns an instance of `ActiveQuery` which is a subclass of `Query`. The [[yii\db\ActiveRecord::find()|find()]] method returns an instance of [[yii\db\ActiveQuery|ActiveQuery]]
Therefore, you can use all query methods of `Query`. which is a subclass of [[yii\db\Query]]. Therefore, you can use all query methods of [[yii\db\Query]].
Instead of returning ActiveRecord objects, you may call `ActiveQuery::asArray()` to Instead of returning ActiveRecord objects, you may call [[yii\db\ActiveQuery::asArray()|ActiveQuery::asArray()]] to
return results in terms of arrays. This is more efficient and is especially useful return results in terms of arrays. This is more efficient and is especially useful
when you need to return a large number of records: when you need to return a large number of records:
...@@ -459,7 +466,7 @@ By default, ActiveRecord now only saves dirty attributes. In 1.1, all attributes ...@@ -459,7 +466,7 @@ By default, ActiveRecord now only saves dirty attributes. In 1.1, all attributes
are saved to database when you call `save()`, regardless of having changed or not, are saved to database when you call `save()`, regardless of having changed or not,
unless you explicitly list the attributes to save. unless you explicitly list the attributes to save.
Scopes are now defined in a custom `ActiveQuery` class instead of model directly. Scopes are now defined in a custom [[yii\db\ActiveQuery|ActiveQuery]] class instead of model directly.
See [active record docs](active-record.md) for more details. See [active record docs](active-record.md) for more details.
...@@ -484,9 +491,9 @@ different DBMS. ...@@ -484,9 +491,9 @@ different DBMS.
User and IdentityInterface User and IdentityInterface
-------------------------- --------------------------
The `CWebUser` class in 1.1 is now replaced by `\yii\Web\User`, and there is no more The `CWebUser` class in 1.1 is now replaced by [[yii\web\User]], and there is no more
`CUserIdentity` class. Instead, you should implement the `IdentityInterface` which `CUserIdentity` class. Instead, you should implement the [[yii\web\IdentityInterface]] which
is much more straightforward to implement. The bootstrap application provides such an example. is much more straightforward to implement. The advanced application template provides such an example.
URL Management URL Management
......
...@@ -169,7 +169,7 @@ In order to use parameterized hostnames, simply declare URL rules with host info ...@@ -169,7 +169,7 @@ In order to use parameterized hostnames, simply declare URL rules with host info
In the above example the first segment of the hostname is treated as the user parameter while the first segment In the above example the first segment of the hostname is treated as the user parameter while the first segment
of the path info is treated as the lang parameter. The rule corresponds to the `user/profile` route. of the path info is treated as the lang parameter. The rule corresponds to the `user/profile` route.
Note that [[UrlManager::showScriptName]] will not take effect when a URL is being created using a rule with a parameterized hostname. Note that [[yii\web\UrlManager::showScriptName]] will not take effect when a URL is being created using a rule with a parameterized hostname.
Also note that any rule with a parameterized hostname should NOT contain the subfolder if the application is under Also note that any rule with a parameterized hostname should NOT contain the subfolder if the application is under
a subfolder of the Web root. For example, if the application is under `http://www.example.com/sandbox/blog`, then we a subfolder of the Web root. For example, if the application is under `http://www.example.com/sandbox/blog`, then we
...@@ -189,9 +189,13 @@ return [ ...@@ -189,9 +189,13 @@ return [
]; ];
``` ```
### Handling REST ### Handling REST requests
TBD: [[\yii\web\VerbFiler]] TBD:
- RESTful routing: [[\yii\web\VerbFilter]], [[\yii\web\UrlManager::$rules]]
- Json API:
- response: [[\yii\web\Response::format]]
- request: [[yii\web\Request::$parsers]], [[\yii\web\JsonParser]]
URL parsing URL parsing
......
...@@ -40,12 +40,12 @@ When using composer you add the following to your composer.json in order to add ...@@ -40,12 +40,12 @@ When using composer you add the following to your composer.json in order to add
```json ```json
"require": { "require": {
"yiisoft/yii": "*", "yiisoft/yii": "*",
"yiisoft/yii2": "*", "yiisoft/yii2": "*",
}, },
``` ```
Start from defining your own descendant of [[\yii\BaseYii]]: Start from defining your own descendant of [[yii\BaseYii]]:
```php ```php
$yii2path = '/path/to/yii2'; $yii2path = '/path/to/yii2';
...@@ -59,7 +59,7 @@ Yii::$classMap = include($yii2path . '/classes.php'); ...@@ -59,7 +59,7 @@ Yii::$classMap = include($yii2path . '/classes.php');
``` ```
Now we have a class, which suites Yii2, but causes fatal errors for Yii1. Now we have a class, which suites Yii2, but causes fatal errors for Yii1.
So, first of all, we need to include [[\YiiBase]] of Yii1 source code to our 'Yii' class So, first of all, we need to include `YiiBase` of Yii1 source code to our 'Yii' class
definition file: definition file:
```php ```php
...@@ -76,7 +76,7 @@ Yii::$classMap = include($yii2path . '/classes.php'); ...@@ -76,7 +76,7 @@ Yii::$classMap = include($yii2path . '/classes.php');
``` ```
Using this, defines all necessary constants and autoloader of Yii1. Using this, defines all necessary constants and autoloader of Yii1.
Now we need to add all fields and methods from [[\YiiBase]] of Yii1 to our 'Yii' class. Now we need to add all fields and methods from `YiiBase` of Yii1 to our 'Yii' class.
Unfortunally, there is no way to do so but copy-paste: Unfortunally, there is no way to do so but copy-paste:
```php ```php
......
...@@ -10,7 +10,7 @@ Standard Yii validators ...@@ -10,7 +10,7 @@ Standard Yii validators
Standard Yii validators could be specified using aliases instead of referring to class names. Here's the list of all Standard Yii validators could be specified using aliases instead of referring to class names. Here's the list of all
validators bundled with Yii with their most useful properties: validators bundled with Yii with their most useful properties:
### `boolean`: [[BooleanValidator]] ### `boolean`: [[yii\validation\BooleanValidator|BooleanValidator]]
Checks if the attribute value is a boolean value. Checks if the attribute value is a boolean value.
...@@ -18,15 +18,15 @@ Checks if the attribute value is a boolean value. ...@@ -18,15 +18,15 @@ Checks if the attribute value is a boolean value.
- `falseValue`, the value representing false status. _(0)_ - `falseValue`, the value representing false status. _(0)_
- `strict`, whether to compare the type of the value and `trueValue`/`falseValue`. _(false)_ - `strict`, whether to compare the type of the value and `trueValue`/`falseValue`. _(false)_
### `captcha`: [[CaptchaValidator]] ### `captcha`: [[yii\captcha\CaptchaValidator|CaptchaValidator]]
Validates that the attribute value is the same as the verification code displayed in the CAPTCHA. Should be used together Validates that the attribute value is the same as the verification code displayed in the CAPTCHA. Should be used together
with [[CaptchaAction]]. with [[yii\captcha\CaptchaAction]].
- `caseSensitive` whether the comparison is case sensitive. _(false)_ - `caseSensitive` whether the comparison is case sensitive. _(false)_
- `captchaAction` the route of the controller action that renders the CAPTCHA image. _('site/captcha')_ - `captchaAction` the route of the controller action that renders the CAPTCHA image. _('site/captcha')_
### `compare`: [[CompareValidator]] ### `compare`: [[yii\validation\CompareValidator|CompareValidator]]
Compares the specified attribute value with another value and validates if they are equal. Compares the specified attribute value with another value and validates if they are equal.
...@@ -34,27 +34,28 @@ Compares the specified attribute value with another value and validates if they ...@@ -34,27 +34,28 @@ Compares the specified attribute value with another value and validates if they
- `compareValue` the constant value to be compared with. - `compareValue` the constant value to be compared with.
- `operator` the operator for comparison. _('==')_ - `operator` the operator for comparison. _('==')_
### `date`: [[DateValidator]] ### `date`: [[yii\validation\DateValidator|DateValidator]]
Verifies if the attribute represents a date, time or datetime in a proper format. Verifies if the attribute represents a date, time or datetime in a proper format.
- `format` the date format that the value being validated should follow according to [[http://www.php.net/manual/en/datetime.createfromformat.php]]. _('Y-m-d')_ - `format` the date format that the value being validated should follow according to
[PHP date_create_from_format](http://www.php.net/manual/en/datetime.createfromformat.php). _('Y-m-d')_
- `timestampAttribute` the name of the attribute to receive the parsing result. - `timestampAttribute` the name of the attribute to receive the parsing result.
### `default`: [[DefaultValueValidator]] ### `default`: [[yii\validation\DefaultValueValidator|DefaultValueValidator]]
Sets the attribute to be the specified default value. Sets the attribute to be the specified default value.
- `value` the default value to be set to the specified attributes. - `value` the default value to be set to the specified attributes.
### `double`: [[NumberValidator]] ### `double`: [[yii\validation\NumberValidator|NumberValidator]]
Validates that the attribute value is a number. Validates that the attribute value is a number.
- `max` limit of the number. _(null)_ - `max` limit of the number. _(null)_
- `min` lower limit of the number. _(null)_ - `min` lower limit of the number. _(null)_
### `email`: [[EmailValidator]] ### `email`: [[yii\validation\EmailValidator|EmailValidator]]
Validates that the attribute value is a valid email address. Validates that the attribute value is a valid email address.
...@@ -63,7 +64,7 @@ Validates that the attribute value is a valid email address. ...@@ -63,7 +64,7 @@ Validates that the attribute value is a valid email address.
- `checkPort` whether to check port 25 for the email address. _(false)_ - `checkPort` whether to check port 25 for the email address. _(false)_
- `enableIDN` whether validation process should take into account IDN (internationalized domain names). _(false)_ - `enableIDN` whether validation process should take into account IDN (internationalized domain names). _(false)_
### `exist`: [[ExistValidator]] ### `exist`: [[yii\validation\ExistValidator|ExistValidator]]
Validates that the attribute value exists in a table. Validates that the attribute value exists in a table.
...@@ -72,7 +73,7 @@ Validates that the attribute value exists in a table. ...@@ -72,7 +73,7 @@ Validates that the attribute value exists in a table.
- `targetAttribute` the ActiveRecord attribute name that should be used to look for the attribute value being validated. - `targetAttribute` the ActiveRecord attribute name that should be used to look for the attribute value being validated.
_(name of the attribute being validated)_ _(name of the attribute being validated)_
### `file`: [[FileValidator]] ### `file`: [[yii\validation\FileValidator|FileValidator]]
Verifies if an attribute is receiving a valid uploaded file. Verifies if an attribute is receiving a valid uploaded file.
...@@ -81,7 +82,7 @@ Verifies if an attribute is receiving a valid uploaded file. ...@@ -81,7 +82,7 @@ Verifies if an attribute is receiving a valid uploaded file.
- `maxSize` the maximum number of bytes required for the uploaded file. - `maxSize` the maximum number of bytes required for the uploaded file.
- `maxFiles` the maximum file count the given attribute can hold. _(1)_ - `maxFiles` the maximum file count the given attribute can hold. _(1)_
### `filter`: [[FilterValidator]] ### `filter`: [[yii\validation\FilterValidator|FilterValidator]]
Converts the attribute value according to a filter. Converts the attribute value according to a filter.
...@@ -102,7 +103,7 @@ Or an anonymous function: ...@@ -102,7 +103,7 @@ Or an anonymous function:
}], }],
``` ```
### `in`: [[RangeValidator]] ### `in`: [[yii\validation\RangeValidator|RangeValidator]]
Validates that the attribute value is among a list of values. Validates that the attribute value is among a list of values.
...@@ -110,7 +111,7 @@ Validates that the attribute value is among a list of values. ...@@ -110,7 +111,7 @@ Validates that the attribute value is among a list of values.
- `strict` whether the comparison is strict (both type and value must be the same). _(false)_ - `strict` whether the comparison is strict (both type and value must be the same). _(false)_
- `not` whether to invert the validation logic. _(false)_ - `not` whether to invert the validation logic. _(false)_
### `inline`: [[InlineValidator]] ### `inline`: [[yii\validation\InlineValidator|InlineValidator]]
Uses a custom function to validate the attribute. You need to define a public method in your Uses a custom function to validate the attribute. You need to define a public method in your
model class which will evaluate the validity of the attribute. For example, if an attribute model class which will evaluate the validity of the attribute. For example, if an attribute
...@@ -125,39 +126,40 @@ public function myValidationMethod($attribute) { ...@@ -125,39 +126,40 @@ public function myValidationMethod($attribute) {
} }
``` ```
### `integer`: [[NumberValidator]] ### `integer`: [[yii\validation\NumberValidator|NumberValidator]]
Validates that the attribute value is an integer number. Validates that the attribute value is an integer number.
- `max` limit of the number. _(null)_ - `max` limit of the number. _(null)_
- `min` lower limit of the number. _(null)_ - `min` lower limit of the number. _(null)_
### `match`: [[RegularExpressionValidator]] ### `match`: [[yii\validation\RegularExpressionValidator|RegularExpressionValidator]]
Validates that the attribute value matches the specified pattern defined by regular expression. Validates that the attribute value matches the specified pattern defined by regular expression.
- `pattern` the regular expression to be matched with. - `pattern` the regular expression to be matched with.
- `not` whether to invert the validation logic. _(false)_ - `not` whether to invert the validation logic. _(false)_
### `number`: [[NumberValidator]] ### `number`: [[yii\validation\NumberValidator|NumberValidator]]
Validates that the attribute value is a number. Validates that the attribute value is a number.
- `max` limit of the number. _(null)_ - `max` limit of the number. _(null)_
- `min` lower limit of the number. _(null)_ - `min` lower limit of the number. _(null)_
### `required`: [[RequiredValidator]] ### `required`: [[yii\validation\RequiredValidator|RequiredValidator]]
Validates that the specified attribute does not have null or empty value. Validates that the specified attribute does not have null or empty value.
- `requiredValue` the desired value that the attribute must have. _(any)_ - `requiredValue` the desired value that the attribute must have. _(any)_
- `strict` whether the comparison between the attribute value and [[requiredValue]] is strict. _(false)_ - `strict` whether the comparison between the attribute value and
[[yii\validation\RequiredValidator::requiredValue|requiredValue]] is strict. _(false)_
### `safe`: [[SafeValidator]] ### `safe`: [[yii\validation\SafeValidator|SafeValidator]]
Serves as a dummy validator whose main purpose is to mark the attributes to be safe for massive assignment. Serves as a dummy validator whose main purpose is to mark the attributes to be safe for massive assignment.
### `string`: [[StringValidator]] ### `string`: [[yii\validation\StringValidator|StringValidator]]
Validates that the attribute value is of certain length. Validates that the attribute value is of certain length.
...@@ -166,7 +168,7 @@ Validates that the attribute value is of certain length. ...@@ -166,7 +168,7 @@ Validates that the attribute value is of certain length.
- `min` minimum length. If not set, it means no minimum length limit. - `min` minimum length. If not set, it means no minimum length limit.
- `encoding` the encoding of the string value to be validated. _([[\yii\base\Application::charset]])_ - `encoding` the encoding of the string value to be validated. _([[\yii\base\Application::charset]])_
### `unique`: [[UniqueValidator]] ### `unique`: [[yii\validation\UniqueValidator|UniqueValidator]]
Validates that the attribute value is unique in the corresponding database table. Validates that the attribute value is unique in the corresponding database table.
...@@ -175,7 +177,7 @@ Validates that the attribute value is unique in the corresponding database table ...@@ -175,7 +177,7 @@ Validates that the attribute value is unique in the corresponding database table
- `targetAttribute` the ActiveRecord attribute name that should be used to look for the attribute value being validated. - `targetAttribute` the ActiveRecord attribute name that should be used to look for the attribute value being validated.
_(name of the attribute being validated)_ _(name of the attribute being validated)_
### `url`: [[UrlValidator]] ### `url`: [[yii\validation\UrlValidator|UrlValidator]]
Validates that the attribute value is a valid http or https URL. Validates that the attribute value is a valid http or https URL.
......
View View
==== ====
The view component is an important part of MVC. The view acts as the interface to the application, making it responsible for presenting data to end users, displaying forms, and so forth. The view component is an important part of MVC. The view acts as the interface to the application, making it responsible
for presenting data to end users, displaying forms, and so forth.
Basics Basics
------ ------
By default, Yii uses PHP in view templates to generate content and elements. A web application view typically contains some combination of HTML, along with PHP `echo`, `foreach`, `if`, and other basic constructs. Using complex PHP code in views is considered to be bad practice. When complex logic and functionality is needed, such code should either be moved to a controller or a widget. By default, Yii uses PHP in view templates to generate content and elements. A web application view typically contains
some combination of HTML, along with PHP `echo`, `foreach`, `if`, and other basic constructs.
Using complex PHP code in views is considered to be bad practice. When complex logic and functionality is needed,
such code should either be moved to a controller or a widget.
The view is typically called from controller action using the `render()` method: The view is typically called from controller action using the [[yii\base\Controller::render()|render()]] method:
```php ```php
public function actionIndex() public function actionIndex()
...@@ -18,11 +22,13 @@ public function actionIndex() ...@@ -18,11 +22,13 @@ public function actionIndex()
} }
``` ```
The first argument to `render()` is the name of the view to display. In the context of the controller, Yii will search for its views in `views/site/` where `site` The first argument to [[yii\base\Controller::render()|render()]] is the name of the view to display.
In the context of the controller, Yii will search for its views in `views/site/` where `site`
is the controller ID. For details on how the view name is resolved, refer to the [[yii\base\Controller::render()]] method. is the controller ID. For details on how the view name is resolved, refer to the [[yii\base\Controller::render()]] method.
The second argument to [[yii\base\Controller::render()|render()]] is a data array of key-value pairs.
The second argument to `render()` is a data array of key-value pairs. Through this array, data can be passed to the view, making the value available in the view as a variable named the same as the corresponding key. Through this array, data can be passed to the view, making the value available in the view as a variable
named the same as the corresponding key.
The view for the action above would be `views/site/index.php` and can be something like: The view for the action above would be `views/site/index.php` and can be something like:
...@@ -32,14 +38,17 @@ The view for the action above would be `views/site/index.php` and can be somethi ...@@ -32,14 +38,17 @@ The view for the action above would be `views/site/index.php` and can be somethi
Any data type can be passed to the view, including arrays or objects. Any data type can be passed to the view, including arrays or objects.
Besides the above `render()` method, the [[yii\web\Controller]] class also provides several other rendering methods. Besides the above [[yii\web\Controller::render()|render()]] method, the [[yii\web\Controller]] class also provides
Below is a summary of these methods: several other rendering methods. Below is a summary of these methods:
* `render()`: renders a view and applies the layout to the rendering result. This is most commonly used to render a complete page. * [[yii\web\Controller::render()|render()]]: renders a view and applies the layout to the rendering result.
* `renderPartial()`: renders a view without applying any layout. This is often used to render a fragment of a page. This is most commonly used to render a complete page.
* `renderAjax()`: renders a view without applying any layout, and injects all registered JS/CSS scripts and files. * [[yii\web\Controller::renderPartial()|renderPartial()]]: renders a view without applying any layout.
It is most commonly used to render an HTML output to respond to an AJAX request. This is often used to render a fragment of a page.
* `renderFile()`: renders a view file. This is similar to `renderPartial()` except that it takes the file path * [[yii\web\Controller::renderAjax()|renderAjax()]]: renders a view without applying any layout, and injects all
registered JS/CSS scripts and files. It is most commonly used to render an HTML output to respond to an AJAX request.
* [[yii\web\Controller::renderFile()|renderFile()]]: renders a view file. This is similar to
[[yii\web\Controller::renderPartial()|renderPartial()]] except that it takes the file path
of the view instead of the view name. of the view instead of the view name.
...@@ -72,10 +81,13 @@ $form = \yii\widgets\ActiveForm::begin([ ...@@ -72,10 +81,13 @@ $form = \yii\widgets\ActiveForm::begin([
\yii\widgets\ActiveForm::end(); \yii\widgets\ActiveForm::end();
``` ```
In the first example in the code above, the `widget` method is used to invoke a widget that just outputs content. In the second example, `begin` and `end` are used for a In the first example in the code above, the [[yii\base\Widget::widget()|widget()]] method is used to invoke a widget
that just outputs content. In the second example, [[yii\base\Widget::begin()|begin()]] and [[yii\base\Widget::end()|end()]]
are used for a
widget that wraps content between method calls with its own output. In case of the form this output is the `<form>` tag widget that wraps content between method calls with its own output. In case of the form this output is the `<form>` tag
with some properties set. with some properties set.
Security Security
-------- --------
...@@ -121,7 +133,7 @@ to learn more refer to [Using template engines](template.md) section of the guid ...@@ -121,7 +133,7 @@ to learn more refer to [Using template engines](template.md) section of the guid
Using View object in templates Using View object in templates
------------------------------ ------------------------------
An instance of `yii\web\View` component is available in view templates as `$this` variable. Using it in templates you An instance of [[yii\web\View]] component is available in view templates as `$this` variable. Using it in templates you
can do many useful things including setting page title and meta, registering scripts and accessing the context. can do many useful things including setting page title and meta, registering scripts and accessing the context.
### Setting page title ### Setting page title
...@@ -185,8 +197,8 @@ Same as with meta tags you can specify additional argument to make sure there's ...@@ -185,8 +197,8 @@ Same as with meta tags you can specify additional argument to make sure there's
### Registering CSS ### Registering CSS
You can register CSS using `registerCss()` or `registerCssFile()`. The former registers a block of CSS code while You can register CSS using [[yii\web\View::registerCss()|registerCss()]] or [[yii\web\View::registerCssFile()|registerCssFile()]].
the latter registers an external CSS file. For example, The former registers a block of CSS code while the latter registers an external CSS file. For example,
```php ```php
$this->registerCss("body { background: #f00; }"); $this->registerCss("body { background: #f00; }");
...@@ -210,23 +222,25 @@ $this->registerCssFile("http://example.com/css/themes/black-and-white.css", [Boo ...@@ -210,23 +222,25 @@ $this->registerCssFile("http://example.com/css/themes/black-and-white.css", [Boo
The code above will add a link to CSS file to the head section of the page. The code above will add a link to CSS file to the head section of the page.
* The first argument specifies the CSS file to be registered. * The first argument specifies the CSS file to be registered.
* The second argument specifies that this CSS file depends on `BootstrapAsset`, meaning it will be added * The second argument specifies that this CSS file depends on [[yii\bootstrap\BootstrapAsset|BootstrapAsset]], meaning it will be added
AFTER the CSS files in `BootstrapAsset`. Without this dependency specification, the relative order AFTER the CSS files in [[yii\bootstrap\BootstrapAsset|BootstrapAsset]]. Without this dependency specification, the relative order
between this CSS file and the `BootstrapAsset` CSS files would be undefined. between this CSS file and the [[yii\bootstrap\BootstrapAsset|BootstrapAsset]] CSS files would be undefined.
* The third argument specifies the attributes for the resulting `<link>` tag. * The third argument specifies the attributes for the resulting `<link>` tag.
* The last argument specifies an ID identifying this CSS file. If it is not provided, the URL of the CSS file will be * The last argument specifies an ID identifying this CSS file. If it is not provided, the URL of the CSS file will be
used instead. used instead.
It is highly recommended that you use [asset bundles](assets.md) to register external CSS files rather than It is highly recommended that you use [asset bundles](assets.md) to register external CSS files rather than
using `registerCssFile()`. Using asset bundles allows you to combine and compress multiple CSS files, which using [[yii\web\View::registerCssFile()|registerCssFile()]]. Using asset bundles allows you to combine and compress
is desirable for high traffic websites. multiple CSS files, which is desirable for high traffic websites.
### Registering scripts ### Registering scripts
With `View` object you can register scripts. There are two dedicated methods for it: `registerJs()` for inline scripts With the [[yii\web\View]] object you can register scripts. There are two dedicated methods for it:
and `registerJsFile()` for external scripts. Inline scripts are useful for configuration and dynamically generated code. [[yii\web\View::registerJs()|registerJs()]] for inline scripts and
[[yii\web\View::registerJsFile()|registerJsFile()]] for external scripts.
Inline scripts are useful for configuration and dynamically generated code.
The method for adding these can be used as follows: The method for adding these can be used as follows:
```php ```php
...@@ -236,11 +250,11 @@ $this->registerJs("var options = ".json_encode($options).";", View::POS_END, 'my ...@@ -236,11 +250,11 @@ $this->registerJs("var options = ".json_encode($options).";", View::POS_END, 'my
The first argument is the actual JS code we want to insert into the page. The second argument The first argument is the actual JS code we want to insert into the page. The second argument
determines where script should be inserted into the page. Possible values are: determines where script should be inserted into the page. Possible values are:
- `View::POS_HEAD` for head section. - [[yii\web\View::POS_HEAD|View::POS_HEAD]] for head section.
- `View::POS_BEGIN` for right after opening `<body>`. - [[yii\web\View::POS_BEGIN|View::POS_BEGIN]] for right after opening `<body>`.
- `View::POS_END` for right before closing `</body>`. - [[yii\web\View::POS_END|View::POS_END]] for right before closing `</body>`.
- `View::POS_READY` for executing code on document `ready` event. This will register jQuery automatically. - [[yii\web\View::POS_READY|View::POS_READY]] for executing code on document `ready` event. This will register [[yii\web\JqueryAsset|jQuery]] automatically.
- `View::POS_LOAD` for executing code on document `load` event. This will register jQuery automatically. - [[yii\web\View::POS_LOAD|View::POS_LOAD]] for executing code on document `load` event. This will register [[yii\web\JqueryAsset|jQuery]] automatically.
The last argument is a unique script ID that is used to identify code block and replace existing one with the same ID The last argument is a unique script ID that is used to identify code block and replace existing one with the same ID
instead of adding a new one. If you don't provide it, the JS code itself will be used as the ID. instead of adding a new one. If you don't provide it, the JS code itself will be used as the ID.
...@@ -251,13 +265,14 @@ An external script can be added like the following: ...@@ -251,13 +265,14 @@ An external script can be added like the following:
$this->registerJsFile('http://example.com/js/main.js', [JqueryAsset::className()]); $this->registerJsFile('http://example.com/js/main.js', [JqueryAsset::className()]);
``` ```
The arguments for `registerJsFile()` are similar to those for `registerCssFile()`. In the above example, The arguments for [[yii\web\View::registerJsFile()|registerJsFile()]] are similar to those for
[[yii\web\View::registerCssFile()|registerCssFile()]]. In the above example,
we register the `main.js` file with the dependency on `JqueryAsset`. This means the `main.js` file we register the `main.js` file with the dependency on `JqueryAsset`. This means the `main.js` file
will be added AFTER `jquery.js`. Without this dependency specification, the relative order between will be added AFTER `jquery.js`. Without this dependency specification, the relative order between
`main.js` and `jquery.js` would be undefined. `main.js` and `jquery.js` would be undefined.
Like `registerCssFile()`, it is also highly recommended that you use [asset bundles](assets.md) to Like for [[yii\web\View::registerCssFile()|registerCssFile()]], it is also highly recommended that you use
register external JS files rather than using `registerJsFile()`. [asset bundles](assets.md) to register external JS files rather than using [[yii\web\View::registerJsFile()|registerJsFile()]].
### Registering asset bundles ### Registering asset bundles
...@@ -267,7 +282,7 @@ details on how to define asset bundles in [asset manager](assets.md) section of ...@@ -267,7 +282,7 @@ details on how to define asset bundles in [asset manager](assets.md) section of
asset bundle, it's very straightforward: asset bundle, it's very straightforward:
```php ```php
frontend\assets\AppAsset::register($this); \frontend\assets\AppAsset::register($this);
``` ```
### Layout ### Layout
...@@ -304,12 +319,13 @@ use yii\helpers\Html; ...@@ -304,12 +319,13 @@ use yii\helpers\Html;
In the markup above there's some code. First of all, `$content` is a variable that will contain result of views rendered In the markup above there's some code. First of all, `$content` is a variable that will contain result of views rendered
with controller's `$this->render()` method. with controller's `$this->render()` method.
We are importing `Html` helper via standard PHP `use` statement. This helper is typically used for almost all views We are importing [[yii\helpers\Html|Html]] helper via standard PHP `use` statement. This helper is typically used for almost all views
where one need to escape outputted data. where one need to escape outputted data.
Several special methods such as `beginPage`/`endPage`, `head`, `beginBody`/`endBody` are triggering page rendering events Several special methods such as [[yii\web\View::beginPage()|beginPage()]]/[[yii\web\View::endPage()|endPage()]],
that are used for registering scripts, links and process page in many other ways. Always include these in your layout in [[yii\web\View::head()|head()]], [[yii\web\View::beginBody()|beginBody()]]/[[yii\web\View::endBody()|endBody()]]
order for rendering to work correctly. are triggering page rendering events that are used for registering scripts, links and process page in many other ways.
Always include these in your layout in order for the rendering to work correctly.
### Partials ### Partials
...@@ -374,7 +390,7 @@ Customizing View component ...@@ -374,7 +390,7 @@ Customizing View component
-------------------------- --------------------------
Since view is also an application component named `view` you can replace it with your own component that extends Since view is also an application component named `view` you can replace it with your own component that extends
from `yii\base\View` or `yii\web\View`. It can be done via application configuration file such as `config/web.php`: from [[yii\base\View]] or [[yii\web\View]]. It can be done via application configuration file such as `config/web.php`:
```php ```php
return [ return [
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment