CDetailView为某个Model显示详细内容。这个要显示的Model可以为CModel或是关联数组。
CDetailView通过配置 attributes来决定Model的那些属性需要显示已经以何种格式显示。
每个属性可以使用Name:Type:Label来配置。其中Type和Label都是可选的。
- “Name” 属性名称.
- “Label” 可以选,属性的标签名,如果没有配置,则使用属性名称做为标签名称.
- “Type” 属性的类型,通过类型来决定显示的格式 formatter.可以使用的类型有 raw, text, ntext, html, date, time, datetime, boolean, number, email, image, url. 等,缺省使用text.
本例修改上例Yii Framework 开发教程(30) Zii组件-ListView 示例 ,修改显示列表的列表项模版_view.php ,使客户名称由普通文字变为Link。
- <h3><?php echo CHtml::link($data->FirstName . ' ' . $data->LastName,
- $this->createUrl('view',array('CustomerId'=>$data->CustomerId)));?></h3>
<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,
- ),
- ),
- ));
- ?>
<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示例
- public function relations()
- {
- return array(
- 'employee'=>array(self::BELONGS_TO,
- 'Employee', 'SupportRepId'),
- );
- }
public function relations()
{
return array(
'employee'=>array(self::BELONGS_TO,
'Employee', 'SupportRepId'),
);
}
显示结果如下:
![201212128005](https://i-blog.csdnimg.cn/blog_migrate/d4d26f4fc1a5f7f072d9f89f14c243f7.png)