Yii2 Listview dynamically update dataProvider

I have a Listview from which I would like to dynamically update with a dataProvider

single click of a button.

itemController.php

:

  <?php
    public function actionList($category = ''){
      $this->layout = '_notags';
      $query['published'] = 1;
      if(!empty($category)){
        $category = category::findOne(['title'=>$category])->id;
        $query['category_id'] = $category;
      }

        echo "<script>console.log('$category')</script>";

      $items = new ActiveDataProvider([
                    'query' => Item::find()->where($query)->orderBy('date_created DESC'),
                    'pagination' => [
                        'pageSize' => 9
                    ],
                  ]);
      return $this->render('_fresh', [
          'newitems' => $items,
          'category' => $category
      ]);
    }
    ?>

      

_list.php

:

<?php
use yii\widgets\ListView;
use kop\y2sp\ScrollPager;
use yii\helpers\HtmlPurifier;
use yii\widgets\Pjax;

if(empty($category))
$genre = '';

$listview = ListView::widget([
      'id' => 'freshitems',
       'dataProvider' => $newitems,
       'itemOptions' => ['class' => 'col-xs-4 featured-item-'.$category],
       'itemView' => '_item',
       'pager' => ['negativeMargin'=>250, 'delay'=>0, 'spinnerSrc'=> '/img/loading.png','triggerOffset' => 3, 'class' => ScrollPager::className(), 'item'=>'.featured-item-' . $genre, 'enabledExtensions'=> Array( ScrollPager::EXTENSION_TRIGGER, ScrollPager::EXTENSION_SPINNER, ScrollPager::EXTENSION_NONE_LEFT, ScrollPager::EXTENSION_PAGING ) ],
       //'summary' => false
  ]);

  $this->registerJsFile('@web/js/main.js');
  $this->registerJsFile('@web/js/jquery.quickfit.js');

  Pjax::begin(['id'=>'freshitems']);
      echo HtmlPurifier::process(
       $listview
     );
  Pjax::end();

?>

      

main.js

:

$(document).ready(function() {
  $(".category-select").click("pjax:end", function() {
      $.pjax.reload({container:"#freshitems"});  //Reload GridView
  });
});

      

I tried using jQuery to change the div containing the _list:

index.php:

  Some categories $ this-> render ('_ list.php', $ category)   

main.js

:

$('.btn').click(function(){
  $('#list-container').load("item/list/" + $(this).id;
});

      

Doing this changes the listview, but it buggy the ScrollPager plugin (the infinite scroller no longer works as expected).

What would be the best way to dynamically change the ListView's dataProvider (or listView entirely) in my opinion?

+3


source to share


1 answer


You can make an AJAX request to an action on your controller, return the render from there (preferably in a new view file, using the DataProvider it receives as a parameter), and then clear the HTML and then add it. Assuming you are putting the ListView inside a container with some id to keep it simpler.



0


source







All Articles