具有beforeValidate()值的yii2 gridview过滤器

时间:2017-02-03 09:41:23

标签: gridview yii2

我有一个yii2 GridView,由gii CRUD生成。

我将浏览器指向/model/index。我在GET字符串中包含任何搜索值。但GridView过滤器预先填充了值。 enter image description here

即使我尝试删除或替换这些过滤器值,预先填充的值也会重新开始。

我注意到这些预先填充的值来自模型的beforeValidate()方法。

public function beforeValidate()
{
    if (parent::beforeValidate()) {
        if ($this->isNewRecord) {
            $this->created_at = time();
            $this->b_soft_deleted = 0;
        }
        $this->updated_at = time();
        return true;
    }           
    return false;
}

显然,GridView过滤器调用beforeValidate()并将这些值用于过滤器......

  • 为什么会这样?
  • 如何为过滤器值获取干净的平板?

(在php 7.0.14上运行yii2 2.0.10)

更新我的搜索模型

<?php

namespace common\models\generated;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\Article;

/**
 * ArticleSearch represents the model behind the search form about     `common\models\Article`.
 */
class ArticleSearch extends Article
{
/**
 * @inheritdoc
 */
public function rules()
{
    return [
        [['id', 'title', 'description', 'positive_keywords', 'negative_keywords'], 'safe'],
        [['created_at', 'updated_at', 'b_soft_deleted'], 'integer'],
    ];
}

/**
 * @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 = Article::find();

    // add conditions that should always apply here

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
    ]);

    $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([
        'created_at' => $this->created_at,
        'updated_at' => $this->updated_at,
        'b_soft_deleted' => $this->b_soft_deleted,
    ]);

    $query->andFilterWhere(['like', 'id', $this->id])
        ->andFilterWhere(['like', 'title', $this->title])
        ->andFilterWhere(['like', 'description', $this->description])
        ->andFilterWhere(['like', 'positive_keywords', $this->positive_keywords])
        ->andFilterWhere(['like', 'negative_keywords', $this->negative_keywords]);

    return $dataProvider;
}

}

2 个答案:

答案 0 :(得分:6)

您正在设置beforeValidate()中的属性,这些属性在调用$this->validate()时应用(无论验证结果如何)。

您需要将此设置移动到其他位置或...

如果我正确猜测你确实设置了created_atupdated_at,因为这些字段在数据库中标记为 not null ,因为gii生成了{{1他们的规则。
处理此类属性的正确方法是删除required规则并添加required,以便在模型保存步骤中设置它们。
这样您就不会看到模型的验证错误,也不必手动设置这些错误,并且数据库列已正确填充。

这整个GridView问题都消失了。

答案 1 :(得分:1)

基于Bizley解决方案,我们也可能不使用TimestampBehavior,我们应该取消所需的,然后将该逻辑放在beforeSave中。如果您想要做任何逻辑或创建一些预先制定的值,这是更通用的解决方案。