You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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\i18n\Formatter;
  11. use yii\base\InvalidConfigException;
  12. use yii\base\Model;
  13. use yii\base\Widget;
  14. use yii\helpers\ArrayHelper;
  15. use yii\helpers\Html;
  16. use yii\helpers\Inflector;
  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. * ~~~
  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. * ],
  40. * ]);
  41. * ~~~
  42. *
  43. * @author Qiang Xue <qiang.xue@gmail.com>
  44. * @since 2.0
  45. */
  46. class DetailView extends Widget
  47. {
  48. /**
  49. * @var array|object the data model whose details are to be displayed. This can be a [[Model]] instance,
  50. * an associative array, an object that implements [[Arrayable]] interface or simply an object with defined
  51. * public accessible non-static properties.
  52. */
  53. public $model;
  54. /**
  55. * @var array a list of attributes to be displayed in the detail view. Each array element
  56. * represents the specification for displaying one particular attribute.
  57. *
  58. * An attribute can be specified as a string in the format of "attribute", "attribute:format" or "attribute:format:label",
  59. * where "attribute" refers to the attribute name, and "format" represents the format of the attribute. The "format"
  60. * is passed to the [[Formatter::format()]] method to format an attribute value into a displayable text.
  61. * Please refer to [[Formatter]] for the supported types. Both "format" and "label" are optional.
  62. * They will take default values if absent.
  63. *
  64. * An attribute can also be specified in terms of an array with the following elements:
  65. *
  66. * - attribute: the attribute name. This is required if either "label" or "value" is not specified.
  67. * - label: the label associated with the attribute. If this is not specified, it will be generated from the attribute name.
  68. * - value: the value to be displayed. If this is not specified, it will be retrieved from [[model]] using the attribute name
  69. * by calling [[ArrayHelper::getValue()]]. Note that this value will be formatted into a displayable text
  70. * according to the "format" option.
  71. * - format: the type of the value that determines how the value would be formatted into a displayable text.
  72. * Please refer to [[Formatter]] for supported types.
  73. * - visible: whether the attribute is visible. If set to `false`, the attribute will NOT be displayed.
  74. */
  75. public $attributes;
  76. /**
  77. * @var string|callable the template used to render a single attribute. If a string, the token `{label}`
  78. * and `{value}` will be replaced with the label and the value of the corresponding attribute.
  79. * If a callback (e.g. an anonymous function), the signature must be as follows:
  80. *
  81. * ~~~
  82. * function ($attribute, $index, $widget)
  83. * ~~~
  84. *
  85. * where `$attribute` refer to the specification of the attribute being rendered, `$index` is the zero-based
  86. * index of the attribute in the [[attributes]] array, and `$widget` refers to this widget instance.
  87. */
  88. public $template = "<tr><th>{label}</th><td>{value}</td></tr>";
  89. /**
  90. * @var array the HTML attributes for the container tag of this widget. The "tag" option specifies
  91. * what container tag should be used. It defaults to "table" if not set.
  92. * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
  93. */
  94. public $options = ['class' => 'table table-striped table-bordered detail-view'];
  95. /**
  96. * @var array|Formatter the formatter used to format model attribute values into displayable texts.
  97. * This can be either an instance of [[Formatter]] or an configuration array for creating the [[Formatter]]
  98. * instance. If this property is not set, the "formatter" application component will be used.
  99. */
  100. public $formatter;
  101. /**
  102. * Initializes the detail view.
  103. * This method will initialize required property values.
  104. */
  105. public function init()
  106. {
  107. if ($this->model === null) {
  108. throw new InvalidConfigException('Please specify the "model" property.');
  109. }
  110. if ($this->formatter == null) {
  111. $this->formatter = Yii::$app->getFormatter();
  112. } elseif (is_array($this->formatter)) {
  113. $this->formatter = Yii::createObject($this->formatter);
  114. }
  115. if (!$this->formatter instanceof Formatter) {
  116. throw new InvalidConfigException('The "formatter" property must be either a Format object or a configuration array.');
  117. }
  118. $this->normalizeAttributes();
  119. }
  120. /**
  121. * Renders the detail view.
  122. * This is the main entry of the whole detail view rendering.
  123. */
  124. public function run()
  125. {
  126. $rows = [];
  127. $i = 0;
  128. foreach ($this->attributes as $attribute) {
  129. $rows[] = $this->renderAttribute($attribute, $i++);
  130. }
  131. $tag = ArrayHelper::remove($this->options, 'tag', 'table');
  132. echo Html::tag($tag, implode("\n", $rows), $this->options);
  133. }
  134. /**
  135. * Renders a single attribute.
  136. * @param array $attribute the specification of the attribute to be rendered.
  137. * @param integer $index the zero-based index of the attribute in the [[attributes]] array
  138. * @return string the rendering result
  139. */
  140. protected function renderAttribute($attribute, $index)
  141. {
  142. if (is_string($this->template)) {
  143. return strtr($this->template, [
  144. '{label}' => $attribute['label'],
  145. '{value}' => $this->formatter->format($attribute['value'], $attribute['format']),
  146. ]);
  147. } else {
  148. return call_user_func($this->template, $attribute, $index, $this);
  149. }
  150. }
  151. /**
  152. * Normalizes the attribute specifications.
  153. * @throws InvalidConfigException
  154. */
  155. protected function normalizeAttributes()
  156. {
  157. if ($this->attributes === null) {
  158. if ($this->model instanceof Model) {
  159. $this->attributes = $this->model->attributes();
  160. } elseif (is_object($this->model)) {
  161. $this->attributes = $this->model instanceof Arrayable ? $this->model->toArray() : array_keys(get_object_vars($this->model));
  162. } elseif (is_array($this->model)) {
  163. $this->attributes = array_keys($this->model);
  164. } else {
  165. throw new InvalidConfigException('The "model" property must be either an array or an object.');
  166. }
  167. sort($this->attributes);
  168. }
  169. foreach ($this->attributes as $i => $attribute) {
  170. if (is_string($attribute)) {
  171. if (!preg_match('/^([\w\.]+)(:(\w*))?(:(.*))?$/', $attribute, $matches)) {
  172. throw new InvalidConfigException('The attribute must be specified in the format of "attribute", "attribute:format" or "attribute:format:label"');
  173. }
  174. $attribute = [
  175. 'attribute' => $matches[1],
  176. 'format' => isset($matches[3]) ? $matches[3] : 'text',
  177. 'label' => isset($matches[5]) ? $matches[5] : null,
  178. ];
  179. }
  180. if (!is_array($attribute)) {
  181. throw new InvalidConfigException('The attribute configuration must be an array.');
  182. }
  183. if (isset($attribute['visible']) && !$attribute['visible']) {
  184. unset($this->attributes[$i]);
  185. continue;
  186. }
  187. if (!isset($attribute['format'])) {
  188. $attribute['format'] = 'text';
  189. }
  190. if (isset($attribute['attribute'])) {
  191. $attributeName = $attribute['attribute'];
  192. if (!isset($attribute['label'])) {
  193. $attribute['label'] = $this->model instanceof Model ? $this->model->getAttributeLabel($attributeName) : Inflector::camel2words($attributeName, true);
  194. }
  195. if (!array_key_exists('value', $attribute)) {
  196. $attribute['value'] = ArrayHelper::getValue($this->model, $attributeName);
  197. }
  198. } elseif (!isset($attribute['label']) || !array_key_exists('value', $attribute)) {
  199. throw new InvalidConfigException('The attribute configuration requires the "attribute" element to determine the value and display label.');
  200. }
  201. $this->attributes[$i] = $attribute;
  202. }
  203. }
  204. }