【发布时间】:2015-02-02 19:17:51
【问题描述】:
我正在尝试在 Yii2 的 GridView 小部件中设置相关模型的过滤器,但我不断收到错误消息,例如过滤器值必须是整数。
我已关注this question。现在,我有两个型号Services.php 和ServiceCharge.php。
在ServiceCharge.php 中的关系设置如下:
public function getServiceName()
{
return $this->hasOne(Services::className(),['id'=>'service_name']);
}
ServiceChargeSearch.php中的代码是这样的:
<?php
namespace app\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\ServiceCharges;
/**
* ServiceChargesSearch represents the model behind the search form about `app\models\ServiceCharges`.
*/
class ServiceChargesSearch extends ServiceCharges
{
/**
* @inheritdoc
*/
public function attributes()
{
// add related fields to searchable attributes
return array_merge(parent::attributes(), ['serviceName.services']);
}
public function rules()
{
return [
[['id'], 'integer'],
[['charges_cash', 'charges_cashless'], 'number'],
[['id', 'serviceName.services', 'room_category'], 'safe'],
];
}
/**
* @inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params)
{
$query = ServiceCharges::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$dataProvider->sort->attributes['serviceName.services'] = [
'asc' => ['serviceName.services' => SORT_ASC],
'desc' => ['serviceName.services' => SORT_DESC],
];
$query->joinWith(['serviceName']);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
$query->andFilterWhere([
'id' => $this->id,
// 'service_name' => $this->service_name,
'room_category' => $this->room_category,
'charges_cash' => $this->charges_cash,
'charges_cashless' => $this->charges_cashless,
])
->andFilterWhere(['LIKE', 'serviceName.services', $this->getAttribute('serviceName.services')]);
return $dataProvider;
}
}
在我的 Gridview 中是这样设置的:
[
'attribute'=>'service_name',
'value'=>'serviceName.services',
],
正确显示相关模型中的服务名称。
我看不到我做错了什么,但服务属性的过滤器字段根本没有显示。
【问题讨论】:
-
你能把完整的php代码贴在“ServiceChargeSearch.php”中吗?该错误是由于验证器配置不正确
-
@BalajiViswanath - 更新并添加了
serviceChargeSearch.php的完整代码