---
title: "Yii Framework 开发教程(31) Zii组件-DetailView 示例"
author: "mapdigit"
date: "2012-12-30T08:58:00Z"
tags: []
slug: "yii-framework-31-zii-detailview"
draft: false
lastmod: "2013-03-22T14:04:34Z"
id: 1834201
url: "https://mapdigit.iteye.com/blog/1834201"
---

CDetailView为某个Model显示详细内容。这个要显示的Model可以为CModel或是关联数组。

CDetailView通过配置[attributes](http://www.yiiframework.com/doc/api/1.1/CDetailView#attributes)来决定Model的那些属性需要显示已经以何种格式显示。

每个属性可以使用Name:Type:Label来配置。其中Type和Label都是可选的。

- “Name” 属性名称.
- “Label” 可以选，属性的标签名，如果没有配置，则使用属性名称做为标签名称.
- “Type” 属性的类型，通过类型来决定显示的格式[formatter](http://www.yiiframework.com/doc/api/1.1/CDetailView#formatter).可以使用的类型有raw, text, ntext, html, date, time, datetime, boolean, number, email, image, url. 等，缺省使用text.

本例修改上例[Yii Framework 开发教程(30) Zii组件-ListView 示例](http://www.imobilebbs.com/wordpress/archives/4069)，修改显示列表的列表项模版\_view.php ，使客户名称由普通文字变为Link。

```
<h3><?php echo CHtml::link($data->FirstName . ' ' . $data->LastName,
$this->createUrl('view',array('CustomerId'=>$data->CustomerId)));?></h3>
```

当点击客户姓名时，转到链接view.php, 传入参数CustomerId设为Customer 的ID。  
创建View.php，使用CDetailView组件

```
<h2><?php echo 'View Customer'; ?></h2>

<?php $this->widget('zii.widgets.CDetailView', array(
	'data'=>$model,
	'attributes'=>array(

				'FirstName',
				'LastName',
				'Company',
				'Address',
				'City',
				'State',
				'Country',
				'PostalCode',
				'Phone',
				'Fax',
				'Email',
				array(
					'name'=>'Employee',
					'value'=>$model->employee->FirstName,
					),

				),
			));
?>
```

使用缺省的格式显示Customer的每个字段，主要的Employee字段，表Customer定义的是SupportRepId做为外键参考Employee，因此修改类Customer定义Relations，参考[Yii Framework 开发教程(27) 数据库-关联Active Record示例](http://www.imobilebbs.com/wordpress/archives/4052)

```
public function relations()
{
	return array(
		'employee'=>array(self::BELONGS_TO,
		'Employee', 'SupportRepId'),
		);
}
```

显示结果如下：  
[![201212128005](http://www.imobilebbs.com/wordpress/wp-content/uploads/2012/12/201212128005.png)](http://www.imobilebbs.com/wordpress/archives/4074/attachment/201212128005)本例[下载](http://www.imobilebbs.com/download/yii/DetailViewDemo.zip)