Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

236 lines
10KB

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