Fuad Ibrahimov
Fuad Ibrahimov

Reputation: 512

Yii2 and sort in ArrayDataProvider

I am using ArrayDataProvider and i want to know how to make the sort links in view like a $sort->link('date') in yii/data/Sort

Upvotes: 3

Views: 10909

Answers (1)

leninhasda
leninhasda

Reputation: 1730

Follow this (yii\data\sort) and this (yii\data\ArrayDataProvider) documentation

what you can do is make sort like this:

$sort = new Sort([
    'attributes' => [
        'age',
        'name' => [
            'asc' => ['first_name' => SORT_ASC, 'last_name' => SORT_ASC],
            'desc' => ['first_name' => SORT_DESC, 'last_name' => SORT_DESC],
            'default' => SORT_DESC,
            'label' => 'Name',
        ],
        // or any other attribute
    ],
]);

after that you can put it in your array data provider

$query = new Query;
$provider = new ArrayDataProvider([
    'allModels' => $query->from('post')->all(),
    'sort' => $sort, // HERE is your $sort
    'pagination' => [
        'pageSize' => 10,
    ],
]);
// get the posts in the current page
$posts = $provider->getModels();

and finally in your view:

// any attribute you defined in your sort defination
echo $sort->link('name') . ' | ' . $sort->link('age');

Upvotes: 11

Related Questions