D
D
Dmitry2018-04-03 21:44:41
Yii
Dmitry, 2018-04-03 21:44:41

Pjax how to switch view for data?

Good evening.
There is an ad site.
It is necessary to organize the output of ads with two different views (list, tiles). The choice of representation should be carried out by clicking on the corresponding link.
Now there is a code

// ССЫЛКИ ДЛЯ ВЫБОРА ФОРМАТА ВЫВОДА.
<?= Html::a('List', ['car/view-mode'], ['data' => ['view-mode' => 1]]) ?>
<?= Html::a('Gallery', ['car/view-mode'], ['data' => ['view-mode' => 2]]) ?>

// ДЕЙСТВИЕ В КОНТРОЛЛЕРЕ УСТАНАВЛИВАЕТ COOKIE
// кроме этого действия в контроллере есть ещё одно действие actionSearchCar(), которое осуществляет поиск и вывод объявлений.
//но его использовать очень не удобно,
// много кода, куча условий, легко поломать, тяжело исправить.
<?php
    public function actionViewMode($id)
    {
        if(Yii::$app->request->isAjax){
            $viewModeCookie = Yii::$app->response->cookies;
            $viewModeCookie->add(new \yii\web\Cookie([
                    'name' => 'view-mode',
                    'value' => $id
                ])
            );
            $render_file = ($id == 1) ? '_gallery' : '_list';
            return $this->renderAjax('_includes/' . $render_file);
        }
    }
 ?>   

// ВЫВОД ДАННЫХ НА СТРАНИЦЕ
<?php Pjax::begin([
    'id' => 'view-mode-pjax',
    'timeout' => 10000,
    'enablePushState' => false,
    'enableReplaceState' => false,
    'linkSelector' => '.vmpjax'
]) ?>

<div id="view-mode-pjax">
    
    <!-- ВЫБОР ПОДКЛЮЧАЕМЫХ ФАЙЛОВ ДЛЯ ВЫВОДА ОБЪЯВЛЕНИЙ СПИСКОМ ИЛИ ГАЛЕРЕЕЙ -->
    <?php if($viewModeCookieValue == 2){ ?>

    <?= $this->render('_includes/_list', ['cars_res' => $cars_res, 'pages' => $pages]) ?>

    <?php }elseif ($viewModeCookieValue == 1){ ?>

    <?= $this->render('_includes/_gallery', ['cars_res' => $cars_res, 'pages' => $pages]) ?>

    <?php } ?>
    
</div>
<?php Pjax::end(); ?>

Depending on the value of the cookie, a certain view should be connected.
It turns out that I need to pass an array of get parameters to renderAjax(). But this array can be of impressive size. It includes data on the region, city, brand, model, price, mileage, color, year of manufacture, and so on and so forth.
Therefore, the question arose whether it would be correct to pass this get array through links, in the controller action to pull the necessary data from the database and pass it to the view?
Initially, when you first visit the page, the data is already there. They are displayed taking into account what the user entered in the search form. And in order to change the view, it is necessary to drag the entire set of necessary data again? Or is there some more compact way?
ps You also need to organize the output according to the selected number of ads on the page. The tasks are similar, so I think it will be possible to use solutions for two tasks? Or I'm wrong?
pss Link to the whole controller . The required actions are actionViewMode() and actionSearchCar(). The code is not mine, I inherited it, so do not scold too much)))

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2018-04-03
@slo_nik

Worrying for nothing, problem solved.
When a link is clicked, an ajax action request is sent, where cookies are set, and then the desired block is reloaded in success using PJAX.

$('a.vmpjax').click(function (e) {
        e.preventDefault();

        $(this).addClass('active').closest('li').siblings().find('a').removeClass('active');

        var viewMode = $(this).attr('data-view-mode');
        var url = $(this).attr('href');
            $.ajax({
                type: "GET",
                url: url,
                data: {
                    'id': viewMode
                },
                success: function (data) {
                    $.pjax.reload({container: "#view-mode-pjax", url: window.location.href, timeout: 0 });
                }
            });
    });

Only this code and class for links were added, the rest remained unchanged.
But if someone tells me how to improve it - I will be grateful.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question