2017-02-03 78 views
2

我有一個yii2 GridView,由gii CRUD生成。yii2帶有beforeValidate()值的gridview過濾器

我把我的瀏覽器指向/model/index。 I 不要在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; 
} 

}

+1

你能顯示您的搜索模式? – Bizley

回答

5

您在beforeValidate()其中應用設置屬性當調用$this->validate()時(不管驗證結果如何)。

您需要將它設置別的地方或...

如果我猜正確你設置created_atupdated_at,因爲這些領域中被標記爲你的數據庫NOT NULL和因爲GII的生成required規則。
處理這些屬性的正確方法是刪除它們的required規則並添加yii\behaviors\TimestampBehavior,該規則負責在模型保存步驟中設置它們。
通過這種方式,您不會看到模型的驗證錯誤,也無需手動設置這些數據並正確填充數據庫列。

而這整個GridView問題已經消失。

+0

是的,你猜對了。我將這個工作到'TimestampBehavior'。非常感謝! –

1

基於Bizley解決方案,我們也可能不使用TimestampBehavior,只是我們應該取消所需的,然後將該邏輯放在beforeSave。如果您想要執行任何邏輯或創建一些預先創建的值,則這是更一般的解決方案。