Yii2 DetailView用法
控制器代码
public function actionDetailView(){
//获取一条记录
$model = Resource::find()->with(['resourceType'])->where(['id'=>7])->one();
return $this->render('detail-view',[
'model'=>$model
]);
}
视图代码
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
?>
<?= DetailView::widget([ // 调用 DetailView::widget() 方法
'model' => $model, // model 这里可以是一个模型类的实例,也可以是一个数组
'attributes' => [ // attributes 属性决定显示模型的那些属性以及如何格式化
[
'attribute' => 'title',
'format' => 'raw',
'value' => function ($model) {
//链接跳转
return Html::a($model->title, ['test/index', 'id' => $model->id], ['title' => '查看']);
}
],
[
'label' => '类型',
'filter' => false, //不显示搜索框
'value' => function ($model) {
$type = [1=>'PC',2=>'VR'];
return $type[$model->type];
},
'format' => 'raw',
],
[
'attribute' => 'url',
'label' => '文件',
'format' =>
[
'image',
[
'width' => '25',
'height' => '25'
]
],
'value' => function($model){
return $model->url;
}
],
[
'attribute'=>'created_at',
'value'=>date('Y-m-d H:i:s',$model->created_at),
],
[
'attribute' => 'status',
'label'=>'状态',
'value'=> function($model){
$status = [-1=>'删除',0=>'未启用',1=>'启用'];
return $status[$model->status];
}
],
],
'template' => '<tr><th>{label}</th><td>{value}</td></tr>',
'options' => ['class' => 'table table-striped table-bordered detail-view'], // 'options' 属性调整真个 table 的样式
]) ?>
显示效果
![]()