X
X
xCEZAREx2016-01-28 11:47:54
JavaScript
xCEZAREx, 2016-01-28 11:47:54

How to make ListView with custom filter (Ajax/Pjax) and pagination in Yii2?

Good afternoon. Prompt with the solution: It is necessary to connect ajax data update through a custom form with filters and dynamic pagination.

Now made through Pjax.
Performance:

<?php Pjax::begin(); ?>
<?= Html::beginForm(['fields/index'], 'post', ['data-pjax' => '', 'class' => 'form-inline']); ?>
<?= Html::input('text', 'string', '', ['class' => 'form-control']) ?>
<?= Html::submitButton('Search It', ['class' => 'btn btn-lg btn-primary', 'name' => 'hash-button']) ?>
<?= Html::endForm() ?>
    <?= ListView::widget([
        'dataProvider' => $dataProvider,
        'itemView' => '_pjax',
        'options' => [
            'id' => 'listview'
        ]
    ]); ?>
<?php Pjax::end(); ?>


action preparation:
$query = Fields::find();

$query->where(['>=', 'field_value', Yii::$app->request->post('string') ?? 0]);

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

return $this->render('index', [
    'dataProvider' => $dataProvider
]);


I set the search criteria - everything is found, but a click on pagination, the ListView is updated without taking into account the filter, because The paginator sends data via GET.

I tried to update the contents of the div through a simple ajax in which I display another view with the ListView as renderPartial, but the pagination redirects to the renderPartial of this same ListView.

I use ListView because I need normal pagination, so there is no desire to invent a wheel. I read on the Yii2 forum that Pjax is not the best solution, but so far only with it has achieved the most optimal result. I found this option https://toster.ru/q/206776 , an error occurs in the console that the id of the declared container was not found, when I substitute my own - the content is not updated and there are no errors.

Can you tell me how to link my form filters and pagination so that everything is updated dynamically?

There is an option to intercept a click on the paginator, but then you need to show the current page. If there is no solution, then tell me how to override the standard paginator or write your own.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Igor Vasiliev, 2017-05-24
@Isolution666

Well, firstly, you need to understand that Ajax is a technology that is maximally related to the javascript language
. To update information on Ajax, you need to create a field (DOM tree) with a certain id that will be tied to the function.
Pjax is just an auxiliary class, a tool for manipulating content, so the networks of the block with the Pjax class should be spread out exactly as much as it will concern updating the content.
In some cases, I had to capture the entire page of the action in view, paganization can be displayed separately, outside the ListView, and this technology is described in the Yii2 documentation the code is more convenient and simple:

public function actionMessages($id ='', $token ='')
    {

        $model = new Message(); // обращаемся к классу привязанному к таблице БД
            if ($model->load(Yii::$app->request->post()) && $model->save()) // убеждаемся что передача данных проходит успешно
            {
                $model = new Message(); // возвращаем то что обновили
            }    

        $send = Message::find()->where(['token' => $token])->orderBy(['id' => SORT_ASC ])->all(); // выводим всю переписку с конкретным пользователем
        $col = Message::find()->where(['token' => $token])->count(); // выводим количество сообщений с конкретным пользователем (например, чтобы скрыть пустой код, если переписки ещё не было)
        $getm = User::find()->where(['id' => $id])->one(); // так мы определим с кем мы переписываемся (имя, аватарка, возраст, что угодно)
        
        return $this->render('messages', ['model' => $model, 'col' => $col, 'send' => $send, 'getm' => $getm, 'id' => $id, 'token' => $token,]); // рендерим всё к чему прикоснулись, чтобы работало.
    }

Everything seems to be clear, and it all works inside the "jacket", through javascript for a specific id in the div block, maybe someone has already found a ready-made solution, I'm just sharing my modest experience.
As for the pagination class specifically:
<?php
use yii\data\Pagination;
?>

This class works well with the class:
<?php
use yii\widgets\LinkPager;
?>

Which needs to be written in the view, and write down such a not tricky construction:
Where the pagination itself should be displayed. As mentioned above, you need to apply a certain id to the code above, I think how to write it in the code - you know, if suddenly the tricks with the ListView did not work.
Nobody needs crutches, but if you need to solve something urgently, then the working code will do:
Controller::action /
$query = Guestbook::find()->where(['level' => 1])->orderBy(['time' => SORT_DESC,]); // создаём конструкцию обращения
        $pages = new Pagination(['totalCount' => $query->count(),'pageSize' => 5]); // обращаемся к классу чтобы сказать сколько записей за раз нужно отобразить, например 5
        $pages->pageSizeParam = false; // отключаем самодеятельность параметров
        $models = $query->offset($pages->offset)->limit($pages->limit)->all(); // теперь зная количество записей и лимиты, мы заставляем скрипт показывать нам ровно столько сколько нам нужно

As far as I know, tags and IDs can be written in the ListView itself, the class is not picky, lightweight and flexible, it solves almost all the needs and whims of customers, read about all the possibilities here: https://xn--d1acnqm.xn--j1amh /%D0%B7%D0%B0%D0%BF%D... and here: www.yiiframework.com/doc-2.0/yii-widgets-linkpager.html I think this will be a nice reading, because there are a lot of answers here and solutions.
and finally a link that helped me a lot: https://nix-tips.ru/examples/simplegridview/index
Thank you for your attention.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question