Skip to content

Instantly share code, notes, and snippets.

@jacksontong
Created August 6, 2017 03:50
Show Gist options
  • Select an option

  • Save jacksontong/36c269098f00d2c37ccda8fd47eed8ff to your computer and use it in GitHub Desktop.

Select an option

Save jacksontong/36c269098f00d2c37ccda8fd47eed8ff to your computer and use it in GitHub Desktop.

Revisions

  1. Jackson created this gist Aug 6, 2017.
    81 changes: 81 additions & 0 deletions CustomerSearch.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,81 @@
    <?php

    namespace app\models\search;

    use Yii;
    use yii\base\Model;
    use yii\data\ActiveDataProvider;
    use app\models\Customer;
    use yii\db\Expression;

    /**
    * CustomerSearch represents the model behind the search form about `app\models\Customer`.
    */
    class CustomerSearch extends Customer
    {
    /**
    * @inheritdoc
    */
    public function rules()
    {
    return [
    [['id'], 'integer'],
    [['first_name', 'last_name', 'email', 'address', 'created_at', 'updated_at', 'search_full_name'], '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)
    {
    $fullNameExp = new Expression('CONCAT_WS(" ", first_name, last_name)');
    $query = Customer::find();
    $query->select([
    '*',
    'search_full_name' => $fullNameExp,
    ]);

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

    $query->andFilterWhere(['like', 'first_name', $this->first_name])
    ->andFilterWhere(['like', 'last_name', $this->last_name])
    ->andFilterWhere(['like', $fullNameExp, $this->search_full_name])
    ->andFilterWhere(['like', 'email', $this->email])
    ->andFilterWhere(['like', 'address', $this->address]);

    return $dataProvider;
    }
    }