Yii2 Listview动态更新dataProvider

时间:2015-07-31 17:07:21

标签: yii2 pjax

我有一个Listview,我想通过点击按钮动态更新dataProvider

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
  });
});

我尝试使用jQuery更改包含_list的div:

index.php:     一些类别          $ this-&gt; render(&#39; _list.php&#39;,$ category)     

main.js

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

这样做确实会改变列表视图,但它会使ScrollPager插件出现故障(无限卷轴无法正常工作)。

在我的视图中动态更改Listview的dataProvider(或listView完全)的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

您可以对控制器上的操作发出AJAX请求,从那里返回渲染(最好在新视图文件中,使用它作为参数接收的DataProvider)并清空HTML然后追加它。 假设您将ListView放在具有一些id的容器中,以使其更容易。