DetailView.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\widgets;
  8. use Yii;
  9. use yii\base\Arrayable;
  10. use yii\base\InvalidConfigException;
  11. use yii\base\Model;
  12. use yii\base\Widget;
  13. use yii\helpers\ArrayHelper;
  14. use yii\helpers\Html;
  15. use yii\helpers\Inflector;
  16. use yii\i18n\Formatter;
  17. /**
  18. * DetailView displays the detail of a single data [[model]].
  19. *
  20. * DetailView is best used for displaying a model in a regular format (e.g. each model attribute
  21. * is displayed as a row in a table.) The model can be either an instance of [[Model]]
  22. * or an associative array.
  23. *
  24. * DetailView uses the [[attributes]] property to determines which model attributes
  25. * should be displayed and how they should be formatted.
  26. *
  27. * A typical usage of DetailView is as follows:
  28. *
  29. * ```php
  30. * echo DetailView::widget([
  31. * 'model' => $model,
  32. * 'attributes' => [
  33. * 'title', // title attribute (in plain text)
  34. * 'description:html', // description attribute in HTML
  35. * [ // the owner name of the model
  36. * 'label' => 'Owner',
  37. * 'value' => $model->owner->name,
  38. * ],
  39. * 'created_at:datetime', // creation date formatted as datetime
  40. * ],
  41. * ]);
  42. * ```
  43. *
  44. * For more details and usage information on DetailView, see the [guide article on data widgets](guide:output-data-widgets).
  45. *
  46. * @author Qiang Xue <qiang.xue@gmail.com>
  47. * @since 2.0
  48. */
  49. class DetailView extends Widget
  50. {
  51. /**
  52. * @var array|object the data model whose details are to be displayed. This can be a [[Model]] instance,
  53. * an associative array, an object that implements [[Arrayable]] interface or simply an object with defined
  54. * public accessible non-static properties.
  55. */
  56. public $model;
  57. /**
  58. * @var array a list of attributes to be displayed in the detail view. Each array element
  59. * represents the specification for displaying one particular attribute.
  60. *
  61. * An attribute can be specified as a string in the format of `attribute`, `attribute:format` or `attribute:format:label`,
  62. * where `attribute` refers to the attribute name, and `format` represents the format of the attribute. The `format`
  63. * is passed to the [[Formatter::format()]] method to format an attribute value into a displayable text.
  64. * Please refer to [[Formatter]] for the supported types. Both `format` and `label` are optional.
  65. * They will take default values if absent.
  66. *
  67. * An attribute can also be specified in terms of an array with the following elements:
  68. *
  69. * - `attribute`: the attribute name. This is required if either `label` or `value` is not specified.
  70. * - `label`: the label associated with the attribute. If this is not specified, it will be generated from the attribute name.
  71. * - `value`: the value to be displayed. If this is not specified, it will be retrieved from [[model]] using the attribute name
  72. * by calling [[ArrayHelper::getValue()]]. Note that this value will be formatted into a displayable text
  73. * according to the `format` option. Since version 2.0.11 it can be defined as closure with the following
  74. * parameters:
  75. *
  76. * ```php
  77. * function ($model, $widget)
  78. * ```
  79. *
  80. * `$model` refers to displayed model and `$widget` is an instance of `DetailView` widget.
  81. *
  82. * - `format`: the type of the value that determines how the value would be formatted into a displayable text.
  83. * Please refer to [[Formatter]] for supported types and [[Formatter::format()]] on how to specify this value.
  84. * - `visible`: whether the attribute is visible. If set to `false`, the attribute will NOT be displayed.
  85. * - `contentOptions`: the HTML attributes to customize value tag. For example: `['class' => 'bg-red']`.
  86. * Please refer to [[\yii\helpers\BaseHtml::renderTagAttributes()]] for the supported syntax.
  87. * - `captionOptions`: the HTML attributes to customize label tag. For example: `['class' => 'bg-red']`.
  88. * Please refer to [[\yii\helpers\BaseHtml::renderTagAttributes()]] for the supported syntax.
  89. */
  90. public $attributes;
  91. /**
  92. * @var string|callable the template used to render a single attribute. If a string, the token `{label}`
  93. * and `{value}` will be replaced with the label and the value of the corresponding attribute.
  94. * If a callback (e.g. an anonymous function), the signature must be as follows:
  95. *
  96. * ```php
  97. * function ($attribute, $index, $widget)
  98. * ```
  99. *
  100. * where `$attribute` refer to the specification of the attribute being rendered, `$index` is the zero-based
  101. * index of the attribute in the [[attributes]] array, and `$widget` refers to this widget instance.
  102. *
  103. * Since Version 2.0.10, the tokens `{captionOptions}` and `{contentOptions}` are available, which will represent
  104. * HTML attributes of HTML container elements for the label and value.
  105. */
  106. public $template = '<tr><th{captionOptions}>{label}</th><td{contentOptions}>{value}</td></tr>';
  107. /**
  108. * @var array the HTML attributes for the container tag of this widget. The `tag` option specifies
  109. * what container tag should be used. It defaults to `table` if not set.
  110. * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
  111. */
  112. public $options = ['class' => 'table table-striped table-bordered detail-view'];
  113. /**
  114. * @var array|Formatter the formatter used to format model attribute values into displayable texts.
  115. * This can be either an instance of [[Formatter]] or an configuration array for creating the [[Formatter]]
  116. * instance. If this property is not set, the `formatter` application component will be used.
  117. */
  118. public $formatter;
  119. /**
  120. * Initializes the detail view.
  121. * This method will initialize required property values.
  122. */
  123. public function init()
  124. {
  125. parent::init();
  126. if ($this->model === null) {
  127. throw new InvalidConfigException('Please specify the "model" property.');
  128. }
  129. if ($this->formatter === null) {
  130. $this->formatter = Yii::$app->getFormatter();
  131. } elseif (is_array($this->formatter)) {
  132. $this->formatter = Yii::createObject($this->formatter);
  133. }
  134. if (!$this->formatter instanceof Formatter) {
  135. throw new InvalidConfigException('The "formatter" property must be either a Format object or a configuration array.');
  136. }
  137. $this->normalizeAttributes();
  138. if (!isset($this->options['id'])) {
  139. $this->options['id'] = $this->getId();
  140. }
  141. }
  142. /**
  143. * Renders the detail view.
  144. * This is the main entry of the whole detail view rendering.
  145. */
  146. public function run()
  147. {
  148. $rows = [];
  149. $i = 0;
  150. foreach ($this->attributes as $attribute) {
  151. $rows[] = $this->renderAttribute($attribute, $i++);
  152. }
  153. $options = $this->options;
  154. $tag = ArrayHelper::remove($options, 'tag', 'table');
  155. echo Html::tag($tag, implode("\n", $rows), $options);
  156. }
  157. /**
  158. * Renders a single attribute.
  159. * @param array $attribute the specification of the attribute to be rendered.
  160. * @param int $index the zero-based index of the attribute in the [[attributes]] array
  161. * @return string the rendering result
  162. */
  163. protected function renderAttribute($attribute, $index)
  164. {
  165. if (is_string($this->template)) {
  166. $captionOptions = Html::renderTagAttributes(ArrayHelper::getValue($attribute, 'captionOptions', []));
  167. $contentOptions = Html::renderTagAttributes(ArrayHelper::getValue($attribute, 'contentOptions', []));
  168. return strtr($this->template, [
  169. '{label}' => $attribute['label'],
  170. '{value}' => $this->formatter->format($attribute['value'], $attribute['format']),
  171. '{captionOptions}' => $captionOptions,
  172. '{contentOptions}' => $contentOptions,
  173. ]);
  174. }
  175. return call_user_func($this->template, $attribute, $index, $this);
  176. }
  177. /**
  178. * Normalizes the attribute specifications.
  179. * @throws InvalidConfigException
  180. */
  181. protected function normalizeAttributes()
  182. {
  183. if ($this->attributes === null) {
  184. if ($this->model instanceof Model) {
  185. $this->attributes = $this->model->attributes();
  186. } elseif (is_object($this->model)) {
  187. $this->attributes = $this->model instanceof Arrayable ? array_keys($this->model->toArray()) : array_keys(get_object_vars($this->model));
  188. } elseif (is_array($this->model)) {
  189. $this->attributes = array_keys($this->model);
  190. } else {
  191. throw new InvalidConfigException('The "model" property must be either an array or an object.');
  192. }
  193. sort($this->attributes);
  194. }
  195. foreach ($this->attributes as $i => $attribute) {
  196. if (is_string($attribute)) {
  197. if (!preg_match('/^([^:]+)(:(\w*))?(:(.*))?$/', $attribute, $matches)) {
  198. throw new InvalidConfigException('The attribute must be specified in the format of "attribute", "attribute:format" or "attribute:format:label"');
  199. }
  200. $attribute = [
  201. 'attribute' => $matches[1],
  202. 'format' => isset($matches[3]) ? $matches[3] : 'text',
  203. 'label' => isset($matches[5]) ? $matches[5] : null,
  204. ];
  205. }
  206. if (!is_array($attribute)) {
  207. throw new InvalidConfigException('The attribute configuration must be an array.');
  208. }
  209. if (isset($attribute['visible']) && !$attribute['visible']) {
  210. unset($this->attributes[$i]);
  211. continue;
  212. }
  213. if (!isset($attribute['format'])) {
  214. $attribute['format'] = 'text';
  215. }
  216. if (isset($attribute['attribute'])) {
  217. $attributeName = $attribute['attribute'];
  218. if (!isset($attribute['label'])) {
  219. $attribute['label'] = $this->model instanceof Model ? $this->model->getAttributeLabel($attributeName) : Inflector::camel2words($attributeName, true);
  220. }
  221. if (!array_key_exists('value', $attribute)) {
  222. $attribute['value'] = ArrayHelper::getValue($this->model, $attributeName);
  223. }
  224. } elseif (!isset($attribute['label']) || !array_key_exists('value', $attribute)) {
  225. throw new InvalidConfigException('The attribute configuration requires the "attribute" element to determine the value and display label.');
  226. }
  227. if ($attribute['value'] instanceof \Closure) {
  228. $attribute['value'] = call_user_func($attribute['value'], $this->model, $this);
  229. }
  230. $this->attributes[$i] = $attribute;
  231. }
  232. }
  233. }