sca*_*dge 11
试试这种方式:
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'attribute' => 'an_attributeid',
'label' => 'yourLabel',
'value' => function($model) { return $model->first_name . " " . $model->last_name ;},
],
['class' => 'yii\grid\ActionColumn', ],
],
]); ?>
Run Code Online (Sandbox Code Playgroud)
感谢本教程:Yii 2.0:在 GridView Yii 2.0 中按计算/相关字段过滤和排序
本教程仅在first_name
&last_name
单独搜索时有效,我filter
在search model
.i.e.
'OR CONCAT(first_name, " ", last_name) LIKE "%' . $this->fullName . '%"'
Run Code Online (Sandbox Code Playgroud)
步骤 1:向您的基本 Person 模型添加一个 getter 函数:
设置基础模型
/* Getter for person full name */
public function getFullName() {
return $this->first_name . ' ' . $this->last_name;
}
/* Your model attribute labels */
public function attributeLabels() {
return [
/* Your other attribute labels */
'fullName' => Yii::t('app', 'Full Name')
];
}
Run Code Online (Sandbox Code Playgroud)
第 2 步:将属性 fullName 添加到您的模型 PersonSearch 并配置您的规则。
Setup search model
/* your calculated attribute */
public $fullName;
/* setup rules */
public function rules() {
return [
/* your other rules */
[['fullName'], 'safe']
];
}
/**
* setup search function for filtering and sorting
* based on fullName field
*/
public function search($params) {
$query = Person::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
/**
* Setup your sorting attributes
* Note: This is setup before the $this->load($params)
* statement below
*/
$dataProvider->setSort([
'attributes' => [
'id',
'fullName' => [
'asc' => ['first_name' => SORT_ASC, 'last_name' => SORT_ASC],
'desc' => ['first_name' => SORT_DESC, 'last_name' => SORT_DESC],
'label' => 'Full Name',
'default' => SORT_ASC
],
'country_id'
]
]);
if (!($this->load($params) && $this->validate())) {
return $dataProvider;
}
$this->addCondition($query, 'id');
$this->addCondition($query, 'first_name', true);
$this->addCondition($query, 'last_name', true);
$this->addCondition($query, 'country_id');
/* Setup your custom filtering criteria */
// filter by person full name
$query->andWhere('first_name LIKE "%' . $this->fullName . '%" ' . //This will filter when only first name is searched.
'OR last_name LIKE "%' . $this->fullName . '%" '. //This will filter when only last name is searched.
'OR CONCAT(first_name, " ", last_name) LIKE "%' . $this->fullName . '%"' //This will filter when full name is searched.
);
return $dataProvider;
}
Run Code Online (Sandbox Code Playgroud)
第 3 步:在视图索引文件中配置 gridview 列
设置视图文件
echo GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'fullName',
['class' => 'yii\grid\ActionColumn'],
]
]);
Run Code Online (Sandbox Code Playgroud)