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.

225 satır
9.3KB

  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. */
  76. public $attributes;
  77. /**
  78. * @var string|callable the template used to render a single attribute. If a string, the token `{label}`
  79. * and `{value}` will be replaced with the label and the value of the corresponding attribute.
  80. * If a callback (e.g. an anonymous function), the signature must be as follows:
  81. *
  82. * ```php
  83. * function ($attribute, $index, $widget)
  84. * ```
  85. *
  86. * where `$attribute` refer to the specification of the attribute being rendered, `$index` is the zero-based
  87. * index of the attribute in the [[attributes]] array, and `$widget` refers to this widget instance.
  88. */
  89. public $template = '<tr><th>{label}</th><td>{value}</td></tr>';
  90. /**
  91. * @var array the HTML attributes for the container tag of this widget. The "tag" option specifies
  92. * what container tag should be used. It defaults to "table" if not set.
  93. * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
  94. */
  95. public $options = ['class' => 'table table-striped table-bordered detail-view'];
  96. /**
  97. * @var array|Formatter the formatter used to format model attribute values into displayable texts.
  98. * This can be either an instance of [[Formatter]] or an configuration array for creating the [[Formatter]]
  99. * instance. If this property is not set, the "formatter" application component will be used.
  100. */
  101. public $formatter;
  102. /**
  103. * Initializes the detail view.
  104. * This method will initialize required property values.
  105. */
  106. public function init()
  107. {
  108. if ($this->model === null) {
  109. throw new InvalidConfigException('Please specify the "model" property.');
  110. }
  111. if ($this->formatter === null) {
  112. $this->formatter = Yii::$app->getFormatter();
  113. } elseif (is_array($this->formatter)) {
  114. $this->formatter = Yii::createObject($this->formatter);
  115. }
  116. if (!$this->formatter instanceof Formatter) {
  117. throw new InvalidConfigException('The "formatter" property must be either a Format object or a configuration array.');
  118. }
  119. $this->normalizeAttributes();
  120. if (!isset($this->options['id'])) {
  121. $this->options['id'] = $this->getId();
  122. }
  123. }
  124. /**
  125. * Renders the detail view.
  126. * This is the main entry of the whole detail view rendering.
  127. */
  128. public function run()
  129. {
  130. $rows = [];
  131. $i = 0;
  132. foreach ($this->attributes as $attribute) {
  133. $rows[] = $this->renderAttribute($attribute, $i++);
  134. }
  135. $options = $this->options;
  136. $tag = ArrayHelper::remove($options, 'tag', 'table');
  137. echo Html::tag($tag, implode("\n", $rows), $options);
  138. }
  139. /**
  140. * Renders a single attribute.
  141. * @param array $attribute the specification of the attribute to be rendered.
  142. * @param integer $index the zero-based index of the attribute in the [[attributes]] array
  143. * @return string the rendering result
  144. */
  145. protected function renderAttribute($attribute, $index)
  146. {
  147. if (is_string($this->template)) {
  148. return strtr($this->template, [
  149. '{label}' => $attribute['label'],
  150. '{value}' => $this->formatter->format($attribute['value'], $attribute['format']),
  151. ]);
  152. } else {
  153. return call_user_func($this->template, $attribute, $index, $this);
  154. }
  155. }
  156. /**
  157. * Normalizes the attribute specifications.
  158. * @throws InvalidConfigException
  159. */
  160. protected function normalizeAttributes()
  161. {
  162. if ($this->attributes === null) {
  163. if ($this->model instanceof Model) {
  164. $this->attributes = $this->model->attributes();
  165. } elseif (is_object($this->model)) {
  166. $this->attributes = $this->model instanceof Arrayable ? array_keys($this->model->toArray()) : array_keys(get_object_vars($this->model));
  167. } elseif (is_array($this->model)) {
  168. $this->attributes = array_keys($this->model);
  169. } else {
  170. throw new InvalidConfigException('The "model" property must be either an array or an object.');
  171. }
  172. sort($this->attributes);
  173. }
  174. foreach ($this->attributes as $i => $attribute) {
  175. if (is_string($attribute)) {
  176. if (!preg_match('/^([\w\.]+)(:(\w*))?(:(.*))?$/', $attribute, $matches)) {
  177. throw new InvalidConfigException('The attribute must be specified in the format of "attribute", "attribute:format" or "attribute:format:label"');
  178. }
  179. $attribute = [
  180. 'attribute' => $matches[1],
  181. 'format' => isset($matches[3]) ? $matches[3] : 'text',
  182. 'label' => isset($matches[5]) ? $matches[5] : null,
  183. ];
  184. }
  185. if (!is_array($attribute)) {
  186. throw new InvalidConfigException('The attribute configuration must be an array.');
  187. }
  188. if (isset($attribute['visible']) && !$attribute['visible']) {
  189. unset($this->attributes[$i]);
  190. continue;
  191. }
  192. if (!isset($attribute['format'])) {
  193. $attribute['format'] = 'text';
  194. }
  195. if (isset($attribute['attribute'])) {
  196. $attributeName = $attribute['attribute'];
  197. if (!isset($attribute['label'])) {
  198. $attribute['label'] = $this->model instanceof Model ? $this->model->getAttributeLabel($attributeName) : Inflector::camel2words($attributeName, true);
  199. }
  200. if (!array_key_exists('value', $attribute)) {
  201. $attribute['value'] = ArrayHelper::getValue($this->model, $attributeName);
  202. }
  203. } elseif (!isset($attribute['label']) || !array_key_exists('value', $attribute)) {
  204. throw new InvalidConfigException('The attribute configuration requires the "attribute" element to determine the value and display label.');
  205. }
  206. $this->attributes[$i] = $attribute;
  207. }
  208. }
  209. }