我有一个问题是可以在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
而不是让我的生活变得非常轻松
如果它太复杂,我也可以用这个来管理。
答案 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]);