CDetailView 核心功能
- 單筆模型 (CModel/AR/關聯陣列) 詳細屬性顯示。
- 透過
attributes 陣列配置顯示欄位、格式化類型、自定義標籤。
- 支援
Name:Type:Label 完整規範:Type 決定格式化器 (raw, text, ntext, html, date, time, datetime, boolean, number, email, image, url)。
基本配置範例
// Controller
public function actionView($id) {
$model = Customer::model()->findByPk($id);
if (!$model) throw new CHttpException(404, 'Customer not found');
$this->render('view', ['model' => $model]);
}
// View (view.php)
widget('zii.widgets.CDetailView', [
'data' => $model,
'attributes' => [
'FirstName',
'LastName',
'Company',
'Address',
'City',
'State',
'Country',
'PostalCode',
'Phone',
'Fax',
'Email',
[
'name' => 'Employee', // 虛擬屬性
'value' => $model->employee->FirstName, // 關聯導航
'label' => 'Support Rep',
],
],
]); ?>
屬性配置完整語法
'attributes' => [
'fieldName', // 簡寫:屬性名 = 標籤 = 格式化器預設 text
'fieldName:html', // 指定格式化器
'fieldName:email:Contact Email', // 格式化器 + 自定義標籤
[ // 完整陣列語法
'name' => 'fieldName', // 屬性名 (支援關聯導航: relation.field)
'label' => 'Custom Label', // 顯示標籤
'type' => 'raw', // 格式化器類型
'value' => 'expression', // 自定義值 (PHP 表達式字串或匿名函數 5.3+)
'visible' => true, // 是否顯示
'cssClass' => 'highlight', // 行 CSS 類別
'headerHtmlOptions' => [], // 標籤儲存格 HTML 選項
'contentHtmlOptions' => [], // 內容儲存格 HTML 選項
],
]
內建格式化器類型對照表
| 類型 | 對應格式化器方法 | 輸出範例 |
| raw | 無處理,直接輸出 | <b>Bold</b> |
| text | CHtml::encode | <b>Bold</b> |
| ntext | nl2br + encode | 換行轉 <br> |
| html | CHtml::encode + purifier (需配置) | 安全 HTML |
| date | Yii::app()->dateFormatter->formatDate() | 2023/12/25 |
| time | formatTime() | 14:30:00 |
| datetime | formatDateTime() | 2023/12/25 14:30:00 |
| boolean | 1/0 → Yes/No (可本地化) | Yes / No |
| number | formatNumber() | 1,234.56 |
| email | mailto: 連結 | <a href="mailto:...">...</a> |
| image | <img src="..."> | 圖片顯示 |
| url | <a href="...">...</a> | 超連結 |
關聯導航顯示 (需模型定義 relations)
// Customer.php
public function relations() {
return [
'employee' => [self::BELONGS_TO, 'Employee', 'SupportRepId'],
];
}
// View 中直接使用關聯屬性
'attributes' => [
'FirstName',
'LastName',
'employee.FirstName:firstName:Support Rep First Name', // 關聯導航 + 格式化 + 標籤
'employee.Email:email:Support Rep Email',
]
渲染結果示意

進階:自定義格式化器
// protected/components/MyFormatter.php
class MyFormatter extends CFormatter {
public function formatStatus($value) {
$map = [0 => 'Pending', 1 => 'Active', 2 => 'Closed'];
return isset($map[$value]) ? $map[$value] : 'Unknown';
}
}
// main.php
'components' => [
'format' => ['class' => 'MyFormatter'],
],
// View 使用
'attributes' => [
'Status:status', // 會呼叫 formatStatus()
]
完整範例下載
DetailViewDemo.zip