在listview yii2中显示JSON数据

时间:2015-11-04 04:43:47

标签: json listview yii2 yii2-advanced-app yii2-basic-app

我有一个问题是可以在yii2的列表视图中显示JSON数据吗?

另一个问题是,这是我的view代码

<div class="panel-group" id="accordion">
  <?= \yii\widgets\ListView::widget([
    'dataProvider' => $dataProvider,
    'itemView' => 'listview',
    'layout' => "{pager}\n{items}\n{pager}",
  ]); ?>
</div>

这是我的listview.php文件代码

 <div data-toggle="collapse" href="#collapse'<?= $model->id ?>'" id="title" class="panel-heading ads-heading">
    <h4 class="panel-title"><?= $model->title ?></h4>
    <div class="pull-right">
        <button type="button" id="'<?= $model->id ?>'" onclick="AdsPost(this)"
                class="checkin-btn btn btn-xs btn-danger"> View Ads
        </button>
    </div>
</div>

这是我的controller代码

 public function actionEvent()
 {
    $connection=Yii::$app->db;
    $command = $connection->createCommand("SELECT * from Advertisement where maincategory=2 AND subcategory=5");
    $dataReader=$command->queryAll(); // execute a query SQL

    $dataProvider = new ActiveDataProvider([
        'query' => $data,

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

我也尝试过类似的东西,但它不能正常工作

$query = new Query();
    $query  ->select(['*'])
        ->from('Advertisement')
        ->where('maincategory=1')

    $command = $query->createCommand();

    $data = $command->queryAll();

    $dataProvider = new ActiveDataProvider([
        'query' => $data,

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

那我在这里做错了什么?  我也在问问题来处理JSON数据,因为如果我可以将JSON数据直接发送到Listview而不是让我的生活变得非常轻松

如果它太复杂,我也可以用这个来管理。

1 个答案:

答案 0 :(得分:0)

您可以尝试这两种方式

在这个问题中,错误是分配$ data而不是$ dataReader

public function actionEvent()
{
   $connection=Yii::$app->db;
   $command = $connection->createCommand("SELECT * from Advertisement where maincategory=2 AND subcategory=5");
   $dataReader=$command->queryAll(); // execute a query SQL

   $dataProvider = new ActiveDataProvider([
    'query' => $dataReader,

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

$query = new Query();
$query->from('Advertisement')
    ->where('maincategory = 2 and subcategory = 5');

$command = $query->createCommand();

$data = $command->queryAll();

$dataProvider = new ActiveDataProvider([
    'query' => $data,

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