3

In my user table I have fields like firstname and lastname. then I generated a views using Gii.In my index page now I have Firstname,Lastname,Username etc....

I concatenated my fistname and lastname as Name.

[
  'attribute'=>'firstname',
  'label' => 'Name',
  'format' => 'raw',
  'value' => function ($data) {
   return Html::a($data->Name);
   },
],     

In Model

public function getName()
{
    return $this->firstname.' '.$this->lastname;
}

unfortunately I am unable to search the name field with last name... I need to filter the field with both firstname and lastname.
Can anyone please help me....
Thanks in advance.

1
  • show searchModel . Commented Jan 17, 2017 at 6:46

1 Answer 1

2

This is how you setup search model (I did not include your other columns, so dont forget on those)

You can find more here: http://www.yiiframework.com/wiki/621/filter-sort-by-calculated-related-fields-in-gridview-yii-2-0/

class UserSearch extends User
{
    public $name;

    public function rules()
    {
        return [
            [['name'], 'safe'],
            // some other rules ...
        ];
    }

    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    public function search($params)
    {
        $query = User::find();

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

        $dataProvider->sort->attributes['name'] = [
            'asc' => ['lastname' => SORT_ASC, 'firstname' => SORT_ASC],
            'desc' => ['lastname' => SORT_DESC, 'firstname' => SORT_DESC],
            'label' => 'Name',
            'default' => SORT_ASC
        ];

        $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

        // some other filters ...
        $query->andFilterWhere([
           'or',
            ['like', 'lastname', $this->name],
            ['like', 'firstname', $this->name],
        ]);

        return $dataProvider;
    }
}

And in your gridview instead of

[
  'attribute'=>'firstname',
  // ...
],   

just use

[
  'attribute'=>'name',
],
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.