3
$dataProvider = new ActiveDataProvider([
                'query' => UserProfile::find()->joinWith(['user'])->where(['<>', 'user.status', 0]),
                'sort' => ['attributes' => ['fullname',
                        'phone',
                        'user.username' => [
                            'asc' => ['user.username' => SORT_ASC],
                            'desc' => ['user.username' => SORT_DESC],
                            'default' => SORT_DESC
                        ],
                        'user.email' => [
                            'asc' => ['user.email' => SORT_ASC],
                            'desc' => ['user.email' => SORT_DESC],
                            'default' => SORT_DESC
                        ],
                    ]]
            ]);

Sorting on fullname and phone working good. But I want to add sorting on username and email column.

please correct me.

User and UserProfile table has relation. (user_profile.user_id = user.id)

<?= GridView::widget([
        'dataProvider' => $dataProvider,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],
            [
                'label' => 'Username',
                'value' => 'user.username',
            ],
            [
                'label' => 'Email',
                'value' => 'user.email',
            ],
            'fullname',
            'address',
            'phone',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>

1 Answers1

3

You need add following code. also add public variables in search model. and use these variables in gridview as attribute name.

public $username, $email;

public function rules()
{
    return [
        [['username', 'email'], 'safe'],
    ];
}

 $dataProvider = new ActiveDataProvider([
        'query' => UserProfile::find()->joinWith(['user'])->where(['<>', 'user.status', 0]), 
        'sort' => [ 
            'defaultOrder' => ['user.id' => SORT_DESC] 
        ],
    ]);

$dataProvider->sort->attributes['username'] = [
        'asc' => ['user.username' => SORT_ASC],
        'desc' => ['user.username' => SORT_DESC],
        ];
$dataProvider->sort->attributes['email'] = [
        'asc' => ['user.email' => SORT_ASC],
        'desc' => ['user.email' => SORT_DESC],
        ];

gridview code.

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        [
            'label' => 'Username', (if sort link not appear so, add comment label line)
            'attribute' => 'username',
            'value' => 'user.username',
        ],
        [
            'label' => 'Email', (if sort link not appear so, add comment label line)
            'attribute' => 'email',
            'value' => 'user.email',
        ],
        'fullname',
        'address',
        'phone',

        ['class' => 'yii\grid\ActionColumn'],
    ],
]); ?>
GAMITG
  • 3,670
  • 7
  • 30
  • 50