【问题标题】:Yii2 Grid view sort and filteration using custom labelYii2 Gridview 使用自定义标签进行排序和过滤
【发布时间】:2017-01-17 06:07:44
【问题描述】:

在我的用户表中,我有名字和姓氏等字段。 然后我使用 Gii 生成了一个视图。现在在我的索引页面中我有名字、姓氏、用户名等......

我将我的名字和姓氏连接为姓名。

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

模型

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

很遗憾,我无法使用姓氏搜索名称字段... 我需要过滤包含名字和姓氏的字段。
谁能帮帮我....
提前致谢。

【问题讨论】:

  • 显示searchModel.

标签: php yii grid


【解决方案1】:

这就是你设置搜索模型的方式(我没有包括你的其他列,所以不要忘记那些)

您可以在这里找到更多信息: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;
    }
}

在你的gridview中而不是

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

只是使用

[
  'attribute'=>'name',
],

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-08
    • 2019-01-09
    • 2015-08-07
    • 2015-11-26
    • 1970-01-01
    • 1970-01-01
    • 2010-12-08
    相关资源
    最近更新 更多