CDetailView.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. <?php
  2. /**
  3. * CDetailView class file.
  4. *
  5. * @author Qiang Xue <qiang.xue@gmail.com>
  6. * @link http://www.yiiframework.com/
  7. * @copyright 2008-2013 Yii Software LLC
  8. * @license http://www.yiiframework.com/license/
  9. */
  10. /**
  11. * CDetailView displays the detail of a single data model.
  12. *
  13. * CDetailView is best used for displaying a model in a regular format (e.g. each model attribute
  14. * is displayed as a row in a table.) The model can be either an instance of {@link CModel}
  15. * or an associative array.
  16. *
  17. * CDetailView uses the {@link attributes} property to determines which model attributes
  18. * should be displayed and how they should be formatted.
  19. *
  20. * A typical usage of CDetailView is as follows:
  21. * <pre>
  22. * $this->widget('zii.widgets.CDetailView', array(
  23. * 'data'=>$model,
  24. * 'attributes'=>array(
  25. * 'title', // title attribute (in plain text)
  26. * 'owner.name', // an attribute of the related object "owner"
  27. * 'description:html', // description attribute in HTML
  28. * array( // related city displayed as a link
  29. * 'label'=>'City',
  30. * 'type'=>'raw',
  31. * 'value'=>CHtml::link(CHtml::encode($model->city->name),
  32. * array('city/view','id'=>$model->city->id)),
  33. * ),
  34. * ),
  35. * ));
  36. * </pre>
  37. *
  38. * @property CFormatter $formatter The formatter instance. Defaults to the 'format' application component.
  39. *
  40. * @author Qiang Xue <qiang.xue@gmail.com>
  41. * @package zii.widgets
  42. * @since 1.1
  43. */
  44. class CDetailView extends CWidget
  45. {
  46. private $_formatter;
  47. /**
  48. * @var mixed the data model whose details are to be displayed. This can be either a {@link CModel} instance
  49. * (e.g. a {@link CActiveRecord} object or a {@link CFormModel} object) or an associative array.
  50. */
  51. public $data;
  52. /**
  53. * @var array a list of attributes to be displayed in the detail view. Each array element
  54. * represents the specification for displaying one particular attribute.
  55. *
  56. * An attribute can be specified as a string in the format of "Name:Type:Label".
  57. * Both "Type" and "Label" are optional.
  58. *
  59. * "Name" refers to the attribute name. It can be either a property (e.g. "title") or a sub-property (e.g. "owner.username").
  60. *
  61. * "Label" represents the label for the attribute display. If it is not given, "Name" will be used to generate the appropriate label.
  62. *
  63. * "Type" represents the type of the attribute. It determines how the attribute value should be formatted and displayed.
  64. * It is defaulted to be 'text'.
  65. * "Type" should be recognizable by the {@link formatter}. In particular, if "Type" is "xyz", then the "formatXyz" method
  66. * of {@link formatter} will be invoked to format the attribute value for display. By default when {@link CFormatter} is used,
  67. * these "Type" values are valid: raw, text, ntext, html, date, time, datetime, boolean, number, email, image, url.
  68. * For more details about these types, please refer to {@link CFormatter}.
  69. *
  70. * An attribute can also be specified in terms of an array with the following elements:
  71. * <ul>
  72. * <li>label: the label associated with the attribute. If this is not specified, the following "name" element
  73. * will be used to generate an appropriate label.</li>
  74. * <li>name: the name of the attribute. This can be either a property or a sub-property of the model.
  75. * If the below "value" element is specified, this will be ignored.</li>
  76. * <li>value: the value to be displayed. If this is not specified, the above "name" element will be used
  77. * to retrieve the corresponding attribute value for display. Note that this value will be formatted according
  78. * to the "type" option as described below. This can also be an anonymous function whose return value will be
  79. * used as a value. The signature of the function should be <code>function($data)</code> where data refers to
  80. * the {@link data} property of the detail view widget.</li>
  81. * <li>type: the type of the attribute that determines how the attribute value would be formatted.
  82. * Please see above for possible values.
  83. * <li>cssClass: the CSS class to be used for this item. This option is available since version 1.1.3.</li>
  84. * <li>template: the template used to render the attribute. If this is not specified, {@link itemTemplate}
  85. * will be used instead. For more details on how to set this option, please refer to {@link itemTemplate}.
  86. * This option is available since version 1.1.1.</li>
  87. * <li>visible: whether the attribute is visible. If set to <code>false</code>, the table row for the attribute will not be rendered.
  88. * This option is available since version 1.1.5.</li>
  89. * </ul>
  90. */
  91. public $attributes;
  92. /**
  93. * @var string the text to be displayed when an attribute value is null. Defaults to "Not set".
  94. */
  95. public $nullDisplay;
  96. /**
  97. * @var string the name of the tag for rendering the detail view. Defaults to 'table'.
  98. * If set to null, no tag will be rendered.
  99. * @see itemTemplate
  100. */
  101. public $tagName='table';
  102. /**
  103. * @var string the template used to render a single attribute. Defaults to a table row.
  104. * These tokens are recognized: "{class}", "{label}" and "{value}". They will be replaced
  105. * with the CSS class name for the item, the label and the attribute value, respectively.
  106. * @see itemCssClass
  107. */
  108. public $itemTemplate="<tr class=\"{class}\"><th>{label}</th><td>{value}</td></tr>\n";
  109. /**
  110. * @var array the CSS class names for the items displaying attribute values. If multiple CSS class names are given,
  111. * they will be assigned to the items sequentially and repeatedly.
  112. * Defaults to <code>array('odd', 'even')</code>.
  113. */
  114. public $itemCssClass=array('odd','even');
  115. /**
  116. * @var array the HTML options used for {@link tagName}
  117. */
  118. public $htmlOptions=array('class'=>'detail-view');
  119. /**
  120. * @var string the base script URL for all detail view resources (e.g. javascript, CSS file, images).
  121. * Defaults to null, meaning using the integrated detail view resources (which are published as assets).
  122. */
  123. public $baseScriptUrl;
  124. /**
  125. * @var string the URL of the CSS file used by this detail view. Defaults to null, meaning using the integrated
  126. * CSS file. If this is set false, you are responsible to explicitly include the necessary CSS file in your page.
  127. */
  128. public $cssFile;
  129. /**
  130. * Initializes the detail view.
  131. * This method will initialize required property values.
  132. */
  133. public function init()
  134. {
  135. if($this->data===null)
  136. throw new CException(Yii::t('zii','Please specify the "data" property.'));
  137. if($this->attributes===null)
  138. {
  139. if($this->data instanceof CModel)
  140. $this->attributes=$this->data->attributeNames();
  141. elseif(is_array($this->data))
  142. $this->attributes=array_keys($this->data);
  143. else
  144. throw new CException(Yii::t('zii','Please specify the "attributes" property.'));
  145. }
  146. if($this->nullDisplay===null)
  147. $this->nullDisplay='<span class="null">'.Yii::t('zii','Not set').'</span>';
  148. if(isset($this->htmlOptions['id']))
  149. $this->id=$this->htmlOptions['id'];
  150. else
  151. $this->htmlOptions['id']=$this->id;
  152. if($this->baseScriptUrl===null)
  153. $this->baseScriptUrl=Yii::app()->getAssetManager()->publish(Yii::getPathOfAlias('zii.widgets.assets')).'/detailview';
  154. if($this->cssFile!==false)
  155. {
  156. if($this->cssFile===null)
  157. $this->cssFile=$this->baseScriptUrl.'/styles.css';
  158. Yii::app()->getClientScript()->registerCssFile($this->cssFile);
  159. }
  160. }
  161. /**
  162. * Renders the detail view.
  163. * This is the main entry of the whole detail view rendering.
  164. */
  165. public function run()
  166. {
  167. $formatter=$this->getFormatter();
  168. if ($this->tagName!==null)
  169. echo CHtml::openTag($this->tagName,$this->htmlOptions);
  170. $i=0;
  171. $n=is_array($this->itemCssClass) ? count($this->itemCssClass) : 0;
  172. foreach($this->attributes as $attribute)
  173. {
  174. if(is_string($attribute))
  175. {
  176. if(!preg_match('/^([\w\.]+)(:(\w*))?(:(.*))?$/',$attribute,$matches))
  177. throw new CException(Yii::t('zii','The attribute must be specified in the format of "Name:Type:Label", where "Type" and "Label" are optional.'));
  178. $attribute=array(
  179. 'name'=>$matches[1],
  180. 'type'=>isset($matches[3]) ? $matches[3] : 'text',
  181. );
  182. if(isset($matches[5]))
  183. $attribute['label']=$matches[5];
  184. }
  185. if(isset($attribute['visible']) && !$attribute['visible'])
  186. continue;
  187. $tr=array('{label}'=>'', '{class}'=>$n ? $this->itemCssClass[$i%$n] : '');
  188. if(isset($attribute['cssClass']))
  189. $tr['{class}']=$attribute['cssClass'].' '.($n ? $tr['{class}'] : '');
  190. if(isset($attribute['label']))
  191. $tr['{label}']=$attribute['label'];
  192. elseif(isset($attribute['name']))
  193. {
  194. if($this->data instanceof CModel)
  195. $tr['{label}']=$this->data->getAttributeLabel($attribute['name']);
  196. else
  197. $tr['{label}']=ucwords(trim(strtolower(str_replace(array('-','_','.'),' ',preg_replace('/(?<![A-Z])[A-Z]/', ' \0', $attribute['name'])))));
  198. }
  199. if(!isset($attribute['type']))
  200. $attribute['type']='text';
  201. if(isset($attribute['value']))
  202. $value=is_object($attribute['value']) && get_class($attribute['value']) === 'Closure' ? call_user_func($attribute['value'],$this->data) : $attribute['value'];
  203. elseif(isset($attribute['name']))
  204. $value=CHtml::value($this->data,$attribute['name']);
  205. else
  206. $value=null;
  207. $tr['{value}']=$value===null ? $this->nullDisplay : $formatter->format($value,$attribute['type']);
  208. $this->renderItem($attribute, $tr);
  209. $i++;
  210. }
  211. if ($this->tagName!==null)
  212. echo CHtml::closeTag($this->tagName);
  213. }
  214. /**
  215. * This method is used by run() to render item row
  216. *
  217. * @param array $options config options for this item/attribute from {@link attributes}
  218. * @param string $templateData data that will be inserted into {@link itemTemplate}
  219. * @since 1.1.11
  220. */
  221. protected function renderItem($options,$templateData)
  222. {
  223. echo strtr(isset($options['template']) ? $options['template'] : $this->itemTemplate,$templateData);
  224. }
  225. /**
  226. * @return CFormatter the formatter instance. Defaults to the 'format' application component.
  227. */
  228. public function getFormatter()
  229. {
  230. if($this->_formatter===null)
  231. $this->_formatter=Yii::app()->format;
  232. return $this->_formatter;
  233. }
  234. /**
  235. * @param CFormatter $value the formatter instance
  236. */
  237. public function setFormatter($value)
  238. {
  239. $this->_formatter=$value;
  240. }
  241. }