This commit is contained in:
cuiliang
2016-06-11 19:49:57 +08:00
2065 changed files with 88639 additions and 74804 deletions

View File

@ -17,13 +17,17 @@ The model can be either an instance or subclass of [[\yii\base\Model]] such as a
DetailView uses the [[yii\widgets\DetailView::$attributes|$attributes]] property to determine which model attributes should be displayed and how they
<<<<<<< HEAD
<<<<<<< HEAD
should be formatted. See the [formatter section](output-formatter.md) for available formatting options.
=======
should be formatted. See the [formatter section](output-formatting.md) for available formatting options.
>>>>>>> yiichina/master
=======
should be formatted. See the [formatter section](output-formatting.md) for available formatting options.
>>>>>>> master
A typical usage of DetailView is as follows:
```php
echo DetailView::widget([
'model' => $model,
@ -75,7 +79,7 @@ use yii\helpers\HtmlPurifier;
?>
<div class="post">
<h2><?= Html::encode($model->title) ?></h2>
<?= HtmlPurifier::process($model->text) ?>
</div>
```
@ -107,9 +111,9 @@ These are then also available as variables in the view.
GridView <a name="grid-view"></a>
--------
Data grid or GridView is one of the most powerful Yii widgets. It is extremely useful if you need to quickly build the admin
Data grid or [[yii\grid\GridView|GridView]] is one of the most powerful Yii widgets. It is extremely useful if you need to quickly build the admin
section of the system. It takes data from a [data provider](output-data-providers.md) and renders each row using a set of [[yii\grid\GridView::columns|columns]]
presenting data in the form of a table.
presenting data in the form of a table.
Each row of the table represents the data of a single data item, and a column usually represents an attribute of
the item (some columns may correspond to complex expressions of attributes or static text).
@ -224,20 +228,24 @@ echo GridView::widget([
'format' => ['date', 'php:Y-m-d']
],
],
]);
]);
```
In the above, `text` corresponds to [[\yii\i18n\Formatter::asText()]]. The value of the column is passed as the first
argument. In the second column definition, `date` corresponds to [[\yii\i18n\Formatter::asDate()]]. The value of the
column is, again, passed as the first argument while 'php:Y-m-d' is used as the second argument value.
<<<<<<< HEAD
<<<<<<< HEAD
For a list of available formatters see the [section about Data Formatting](output-formatter.md).
=======
For a list of available formatters see the [section about Data Formatting](output-formatting.md).
>>>>>>> yiichina/master
=======
For a list of available formatters see the [section about Data Formatting](output-formatting.md).
>>>>>>> master
For configuring data columns there is also a shortcut format which is described in the
For configuring data columns there is also a shortcut format which is described in the
API documentation for [[yii\grid\GridView::columns|columns]].
@ -279,7 +287,24 @@ Available properties you can configure are:
- [[yii\grid\ActionColumn::urlCreator|urlCreator]] is a callback that creates a button URL using the specified model information. The signature of
the callback should be the same as that of [[yii\grid\ActionColumn::createUrl()]]. If this property is not set,
button URLs will be created using [[yii\grid\ActionColumn::createUrl()]].
- [[yii\grid\ActionColumn::visibleButtons|visibleButtons]] is an array of visibility conditions for each button.
The array keys are the button names (without curly brackets), and the values are the boolean true/false or the
anonymous function. When the button name is not specified in this array it will be shown by default.
The callbacks must use the following signature:
```php
function ($model, $key, $index) {
return $model->status === 'editable';
}
```
Or you can pass a boolean value:
```php
[
'update' => \Yii::$app->user->can('update')
]
```
#### Checkbox column
@ -309,7 +334,7 @@ var keys = $('#grid').yiiGridView('getSelectedRows');
#### Serial column
Serial column renders row numbers starting with `1` and going forward.
[[yii\grid\SerialColumn|Serial column]] renders row numbers starting with `1` and going forward.
Usage is as simple as the following:
@ -330,13 +355,14 @@ echo GridView::widget([
### Filtering data
For filtering data the GridView needs a [model](structure-models.md) that takes the input from, the filtering
form and adjusts the query of the dataProvider to respect the search criteria.
For filtering data, the GridView needs a [model](structure-models.md) that represents the search criteria which is
usually taken from the filter fields in the GridView table.
A common practice when using [active records](db-active-record.md) is to create a search Model class
that provides needed functionality (it can be generated for you by Gii). This class defines the validation
rules for the search and provides a `search()` method that will return the data provider.
that provides needed functionality (it can be generated for you by [Gii](start-gii.md)). This class defines the validation
rules for the search and provides a `search()` method that will return the data provider with an
adjusted query that respects the search criteria.
To add the search capability for the `Post` model, we can create `PostSearch` like the following example:
To add the search capability for the `Post` model, we can create a `PostSearch` model like the following example:
```php
<?php
@ -372,7 +398,7 @@ class PostSearch extends Post
'query' => $query,
]);
// load the seach form data and validate
// load the search form data and validate
if (!($this->load($params) && $this->validate())) {
return $dataProvider;
}
@ -385,9 +411,11 @@ class PostSearch extends Post
return $dataProvider;
}
}
```
> Tip: See [Query Builder](db-query-builder.md) and especially [Filter Conditions](db-query-builder.md#filter-conditions)
> to learn how to build filtering query.
You can use this function in the controller to get the dataProvider for the GridView:
```php
@ -412,6 +440,83 @@ echo GridView::widget([
]);
```
### Separate filter form
Most of the time using GridView header filters is enough, but in case you need a separate filter form,
you can easily add it as well. You can create partial view `_search.php` with the following contents:
```php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model app\models\PostSearch */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="post-search">
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<?= $form->field($model, 'title') ?>
<?= $form->field($model, 'creation_date') ?>
<div class="form-group">
<?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
<?= Html::submitButton('Reset', ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
```
and include it in `index.php` view like so:
```php
<?= $this->render('_search', ['model' => $searchModel]) ?>
```
> Note: if you use Gii to generate CRUD code, the separate filter form (`_search.php`) is generated by default,
but is commented in `index.php` view. Uncomment it and it's ready to use!
Separate filter form is useful when you need to filter by fields, that are not displayed in GridView
or for special filtering conditions, like date range. For filtering by date range we can add non DB attributes
`createdFrom` and `createdTo` to the search model:
```php
class PostSearch extends Post
{
/**
* @var string
*/
public $createdFrom;
/**
* @var string
*/
public $createdTo;
}
```
Extend query conditions in the `search()` method like so:
```php
$query->andFilterWhere(['>=', 'creation_date', $this->createdFrom])
->andFilterWhere(['<=', 'creation_date', $this->createdTo]);
```
And add the representative fields to the filter form:
```php
<?= $form->field($model, 'creationFrom') ?>
<?= $form->field($model, 'creationTo') ?>
```
### Working with model relations
@ -434,6 +539,7 @@ $dataProvider = new ActiveDataProvider([
// join with relation `author` that is a relation to the table `users`
// and set the table alias to be `author`
$query->joinWith(['author' => function($query) { $query->from(['author' => 'users']); }]);
// since version 2.0.7, the above line can be simplified to $query->joinWith('author AS author');
// enable sorting for the related column
$dataProvider->sort->attributes['author.name'] = [
'asc' => ['author.name' => SORT_ASC],
@ -475,8 +581,9 @@ $query->andFilterWhere(['LIKE', 'author.name', $this->getAttribute('author.name'
> For example, if you use the alias `au` for the author relation table, the joinWith statement looks like the following:
>
> ```php
> $query->joinWith(['author' => function($query) { $query->from(['au' => 'users']); }]);
> $query->joinWith(['author au']);
> ```
>
> It is also possible to just call `$query->joinWith(['author']);` when the alias is defined in the relation definition.
>
> The alias has to be used in the filter condition but the attribute name stays the same:
@ -506,7 +613,7 @@ $query->andFilterWhere(['LIKE', 'author.name', $this->getAttribute('author.name'
#### Using SQL views for filtering, sorting and displaying data
There is also another approach that can be faster and more useful - SQL views. For example, if we need to show the gridview
There is also another approach that can be faster and more useful - SQL views. For example, if we need to show the gridview
with users and their profiles, we can do so in this way:
```sql
@ -608,6 +715,44 @@ echo GridView::widget([
### Using GridView with Pjax
> Note: This section is under development.
The [[yii\widgets\Pjax|Pjax]] widget allows you to update a certain section of a
page instead of reloading the entire page. You can use it to to update only the
[[yii\grid\GridView|GridView]] content when using filters.
TBD
```php
use yii\widgets\Pjax;
use yii\grid\GridView;
Pjax::begin([
// PJax options
]);
Gridview::widget([
// GridView options
]);
Pjax::end();
```
Pjax also works for the links inside the [[yii\widgets\Pjax|Pjax]] widget and
for the links specified by [[yii\widgets\Pjax::$linkSelector|Pjax::$linkSelector]].
But this might be a problem for the links of an [[yii\grid\ActionColumn|ActionColumn]].
To prevent this, add the HTML attribute `data-pjax="0"` to the links when you edit
the [[yii\grid\ActionColumn::$buttons|ActionColumn::$buttons]] property.
#### GridView/ListView with Pjax in Gii
Since 2.0.5, the CRUD generator of [Gii](start-gii.md) has an option called
`$enablePjax` that can be used via either web interface or command line.
```php
yii gii/crud --controllerClass="backend\\controllers\PostController" \
--modelClass="common\\models\\Post" \
--enablePjax=1
```
Which generates a [[yii\widgets\Pjax|Pjax]] widget wrapping the
[[yii\grid\GridView|GridView]] or [[yii\widgets\ListView|ListView]] widgets.
Further reading
---------------
- [Rendering Data in Yii 2 with GridView and ListView](http://www.sitepoint.com/rendering-data-in-yii-2-with-gridview-and-listview/) by Arno Slatius.