我知道有一些与此相关的问题,但他们无法帮助我。
我已生成GridView
,其中包含Sale
模型,我添加了新列,该列来自不同的表,名为price
。现在我想添加排序和过滤,但不知何故它不起作用..
以下是我正在做的事情:
第1步:将函数getItemPrice
添加到Sale model
:
/* Gets item price*/
public function getItemPrice()
{
return $this->item->price;
}
第2步:在SaleSearch
模型中定义价格规则:
/**
* SaleSearch represents the model behind the search form about `app\models\Sale`.
*/
class SaleSearch extends Sale
{
public $price;
/**
* @inheritdoc
*/
public function rules()
{
return [
[['id', 'item_id', 'sign'], 'integer'],
[['customer_name', 'customer_surname', 'customer_phone', 'customer_email', 'code', 'comment'], 'safe'],
[['price'], 'double'],
];
}
第3步:将setSort()
添加到同一模型中并打字joinWith
语句:
public function search($params)
{
$query = Sale::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$query->joinWith('item');
$dataProvider->setSort([
'attributes' => [
'customer_name',
'customer_surname',
'customer_phone',
'customer_email',
'code',
'comment',
'sign',
'price' => [
'asc' =>['tbl_item.price' => SORT_ASC],
'desc' =>['tbl_item.price' => SORT_DESC],
],
'item_id' => [
'asc' =>['item.name' => SORT_ASC],
'desc' =>['item.name' => SORT_DESC],
]
]
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'id' => $this->id,
'item_id' => $this->item_id,
'sign' => $this->sign,
]);
$query->andFilterWhere(['like', 'customer_name', $this->customer_name])
->andFilterWhere(['like', 'customer_surname', $this->customer_surname])
->andFilterWhere(['like', 'customer_phone', $this->customer_phone])
->andFilterWhere(['like', 'customer_email', $this->customer_email])
->andFilterWhere(['like', 'code', $this->code])
->andFilterWhere(['like', 'comment', $this->comment]);
return $dataProvider;
}
}
我的GridView
:
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'attribute' => 'item_id',
'value' => 'item.name',
],
'code',
'customer_name',
'customer_surname',
'customer_phone',
[
'attribute' => 'price',
'value' => function($model) {
return $model->item->price;
},
],
[
'attribute' => 'sign',
'value' => function ($model) {
return $model->sign == 1 ? 'Apmokėtas' : 'Neapmokėtas';
},
],
// 'customer_email:email',
// 'comment:ntext',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
在编写这样的代码之后,我的所有GridView
现在根本没有排序或过滤。有人能告诉我我做错了什么吗?
答案 0 :(得分:0)
您使用代码覆盖Sort
个对象。默认情况下,它会为所有属性准备排序。如果您只想添加一个字段进行排序,请执行以下操作:
$dataProvider->sort->attributes['price'] = [
'asc' => ['tbl_item.price' => SORT_ASC],
'desc' => ['tbl_item.price' => SORT_DESC],
'label' => 'Item price'
];
这样您就不会覆盖默认行为。
答案 1 :(得分:0)
您的属性名称为Kaina
而不是price
。所以,
$dataProvider->sort->attributes['Kaina'] = [
'asc' => ['tbl_item.price' => SORT_ASC],
'desc' => ['tbl_item.price' => SORT_DESC],
'label' => 'Item price'
];