YiiのDetailViewでデータを表示する場合、
<?php $this->widget('bootstrap.widgets.TbDetailView', array( 'data'=>$model, 'attributes'=>array( 'id', 'name', 'email', 'msg', 'htmlmsg', ), )); ?>
のような感じでビューのファイルに記載すると該当モデルの要素を表示してくれます。この際、たとえば、msgのデータに含まれる改行コードについては<br \>にして表示したい場合は、
'msg',
のかわりに
'msg:ntext',
のように書けばよいし、idに更新ページへのリンクを張りたいときは、
'id',
のかわりに
array( 'name'=>'id', 'type'=>'raw', 'value'=>CHtml::link(CHtml::encode($model->id), array('update', 'id'=>$model->id)), ),
のように書けばよいです。
ntextやrawなどはフォーマッターと呼ばれていて、これらの他に以下のようなものが利用できます。(詳しくはこちら)
- raw: the attribute value will not be changed at all.
- text: the attribute value will be HTML-encoded when rendering.
- ntext: the formatNtext method will be called to format the attribute value as a HTML-encoded plain text with newlines converted as the HTML <br /> tags.
- html: the attribute value will be purified and then returned.
- date: the formatDate method will be called to format the attribute value as a date.
- time: the formatTime method will be called to format the attribute value as a time.
- datetime: the formatDatetime method will be called to format the attribute value as a date with time.
- boolean: the formatBoolean method will be called to format the attribute value as a boolean display.
- number: the formatNumber method will be called to format the attribute value as a number display.
- email: the formatEmail method will be called to format the attribute value as a mailto link.
- image: the formatImage method will be called to format the attribute value as an image tag where the attribute value is the image URL.
- url: the formatUrl method will be called to format the attribute value as a hyperlink where the attribute value is the URL.
ただ、利用していると、これら以外にもあったらなぁと思うことがあります。こういう場合、簡単にフォーマッターを自作して利用することができます。たとえば、「HTMLは許可し、かつ、改行は<br />タグに変換する」フォーマッターとしてnhtmlを作成してみます。
まず、protected/extensions/以下にMyFormatter.phpを用意します。内容は以下のような感じです。
class MyFormatter extends CFormatter { public function formatNhtml($value) { return $this->formatHtml(nl2br($value)); } }
次に、このフォーマッターを利用できるようにprotected/config/main.phpに以下を追記します。
'format'=>array( 'class'=>'application.extensions.MyFormatter', ),
以上で完了です。実際に利用する場合は、
'htmlmsg',
のかわりに
'htmlmsg:nhtml',
のように記載すればよいです。