0

我有一个问题,是否可以在 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那会让我的生活变得非常轻松

如果它太复杂,我也无法处理。

4

1 回答 1

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]);
于 2015-11-04T07:55:15.293 回答