DetailView.php 7.7 KB

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