GridView.php 12.6 KB
Newer Older
Qiang Xue committed
1 2 3 4 5 6 7
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

8
namespace yii\grid;
Qiang Xue committed
9 10 11 12 13 14 15 16

use Yii;
use Closure;
use yii\base\Formatter;
use yii\base\InvalidConfigException;
use yii\base\Widget;
use yii\db\ActiveRecord;
use yii\helpers\Html;
17
use yii\helpers\Json;
18
use yii\widgets\BaseListView;
Qiang Xue committed
19 20 21 22 23

/**
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
24
class GridView extends BaseListView
Qiang Xue committed
25 26 27 28 29
{
	const FILTER_POS_HEADER = 'header';
	const FILTER_POS_FOOTER = 'footer';
	const FILTER_POS_BODY = 'body';

30 31 32 33
	/**
	 * @var string the default data column class if the class name is not explicitly specified when configuring a data column.
	 * Defaults to 'yii\grid\DataColumn'.
	 */
Qiang Xue committed
34
	public $dataColumnClass;
35 36 37 38
	/**
	 * @var string the caption of the grid table
	 * @see captionOptions
	 */
Qiang Xue committed
39
	public $caption;
40 41 42 43
	/**
	 * @var array the HTML attributes for the caption element
	 * @see caption
	 */
Alexander Makarov committed
44
	public $captionOptions = [];
45 46 47
	/**
	 * @var array the HTML attributes for the grid table element
	 */
Alexander Makarov committed
48
	public $tableOptions = ['class' => 'table table-striped table-bordered'];
49 50 51
	/**
	 * @var array the HTML attributes for the table header row
	 */
Alexander Makarov committed
52
	public $headerRowOptions = [];
53 54 55
	/**
	 * @var array the HTML attributes for the table footer row
	 */
Alexander Makarov committed
56
	public $footerRowOptions = [];
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
	/**
	 * @var array|Closure the HTML attributes for the table body rows. This can be either an array
	 * specifying the common HTML attributes for all body rows, or an anonymous function that
	 * returns an array of the HTML attributes. The anonymous function will be called once for every
	 * data model returned by [[dataProvider]]. It should have the following signature:
	 *
	 * ~~~php
	 * function ($model, $key, $index, $grid)
	 * ~~~
	 *
	 * - `$model`: the current data model being rendered
	 * - `$key`: the key value associated with the current data model
	 * - `$index`: the zero-based index of the data model in the model array returned by [[dataProvider]]
	 * - `$grid`: the GridView object
	 */
Alexander Makarov committed
72
	public $rowOptions = [];
73 74 75 76 77
	/**
	 * @var Closure an anonymous function that is called once BEFORE rendering each data model.
	 * It should have the similar signature as [[rowOptions]]. The return result of the function
	 * will be rendered directly.
	 */
Qiang Xue committed
78
	public $beforeRow;
79 80 81 82 83
	/**
	 * @var Closure an anonymous function that is called once AFTER rendering each data model.
	 * It should have the similar signature as [[rowOptions]]. The return result of the function
	 * will be rendered directly.
	 */
Qiang Xue committed
84
	public $afterRow;
85 86 87
	/**
	 * @var boolean whether to show the header section of the grid table.
	 */
Qiang Xue committed
88 89
	public $showHeader = true;
	/**
90
	 * @var boolean whether to show the footer section of the grid table.
Qiang Xue committed
91
	 */
92
	public $showFooter = false;
Qiang Xue committed
93 94 95 96 97 98 99 100
	/**
	 * @var array|Formatter the formatter used to format model attribute values into displayable texts.
	 * This can be either an instance of [[Formatter]] or an configuration array for creating the [[Formatter]]
	 * instance. If this property is not set, the "formatter" application component will be used.
	 */
	public $formatter;
	/**
	 * @var array grid column configuration. Each array element represents the configuration
101
	 * for one particular grid column. For example,
Qiang Xue committed
102
	 *
103
	 * ~~~php
Alexander Makarov committed
104 105 106
	 * [
	 *     ['class' => SerialColumn::className()],
	 *     [
107 108 109
	 *         'class' => DataColumn::className(),
	 *         'attribute' => 'name',
	 *         'format' => 'text',
110
	 *         'label' => 'Name',
Alexander Makarov committed
111 112 113
	 *     ],
	 *     ['class' => CheckboxColumn::className()],
	 * ]
114
	 * ~~~
Qiang Xue committed
115
	 *
116 117 118
	 * If a column is of class [[DataColumn]], the "class" element can be omitted.
	 *
	 * As a shortcut format, a string may be used to specify the configuration of a data column
119
	 * which only contains "attribute", "format", and/or "label" options: `"attribute:format:label"`.
120
	 * For example, the above "name" column can also be specified as: `"name:text:Name"`.
121
	 * Both "format" and "label" are optional. They will take default values if absent.
Qiang Xue committed
122
	 */
Alexander Makarov committed
123
	public $columns = [];
Qiang Xue committed
124 125
	public $emptyCell = '&nbsp;';
	/**
126
	 * @var \yii\base\Model the model that keeps the user-entered filter data. When this property is set,
Qiang Xue committed
127 128
	 * the grid view will enable column-based filtering. Each data column by default will display a text field
	 * at the top that users can fill in to filter the data.
129 130 131 132 133
	 *
	 * Note that in order to show an input field for filtering, a column must have its [[DataColumn::attribute]]
	 * property set or have [[DataColumn::filter]] set as the HTML code for the input field.
	 *
	 * When this property is not set (null) the filtering feature is disabled.
Qiang Xue committed
134 135
	 */
	public $filterModel;
136 137 138 139 140 141 142 143
	/**
	 * @var string|array the URL for returning the filtering result. [[Html::url()]] will be called to
	 * normalize the URL. If not set, the current controller action will be used.
	 * When the user makes change to any filter input, the current filtering inputs will be appended
	 * as GET parameters to this URL.
	 */
	public $filterUrl;
	public $filterSelector;
Qiang Xue committed
144 145
	/**
	 * @var string whether the filters should be displayed in the grid view. Valid values include:
146 147 148 149 150 151 152 153
	 *
	 * - [[FILTER_POS_HEADER]]: the filters will be displayed on top of each column's header cell.
	 * - [[FILTER_POS_BODY]]: the filters will be displayed right below each column's header cell.
	 * - [[FILTER_POS_FOOTER]]: the filters will be displayed below each column's footer cell.
	 */
	public $filterPosition = self::FILTER_POS_BODY;
	/**
	 * @var array the HTML attributes for the filter row element
Qiang Xue committed
154
	 */
Alexander Makarov committed
155
	public $filterRowOptions = ['class' => 'filters'];
Qiang Xue committed
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171

	/**
	 * Initializes the grid view.
	 * This method will initialize required property values and instantiate {@link columns} objects.
	 */
	public function init()
	{
		parent::init();
		if ($this->formatter == null) {
			$this->formatter = Yii::$app->getFormatter();
		} elseif (is_array($this->formatter)) {
			$this->formatter = Yii::createObject($this->formatter);
		}
		if (!$this->formatter instanceof Formatter) {
			throw new InvalidConfigException('The "formatter" property must be either a Format object or a configuration array.');
		}
Qiang Xue committed
172 173 174
		if (!isset($this->options['id'])) {
			$this->options['id'] = $this->getId();
		}
175 176 177
		if (!isset($this->filterRowOptions['id'])) {
			$this->filterRowOptions['id'] = $this->options['id'] . '-filters';
		}
Qiang Xue committed
178 179 180 181

		$this->initColumns();
	}

Qiang Xue committed
182 183 184 185 186 187
	/**
	 * Runs the widget.
	 */
	public function run()
	{
		$id = $this->options['id'];
188
		$options = Json::encode($this->getClientOptions());
Qiang Xue committed
189 190
		$view = $this->getView();
		GridViewAsset::register($view);
191
		$view->registerJs("jQuery('#$id').yiiGridView($options);");
Qiang Xue committed
192 193 194
		parent::run();
	}

195 196 197 198 199 200 201

	/**
	 * Returns the options for the grid view JS widget.
	 * @return array the options
	 */
	protected function getClientOptions()
	{
Alexander Makarov committed
202
		$filterUrl = isset($this->filterUrl) ? $this->filterUrl : [Yii::$app->controller->action->id];
203 204 205 206 207 208
		$id = $this->filterRowOptions['id'];
		$filterSelector = "#$id input, #$id select";
		if (isset($this->filterSelector)) {
			$filterSelector .= ', ' . $this->filterSelector;
		}

Alexander Makarov committed
209
		return [
210 211
			'filterUrl' => Html::url($filterUrl),
			'filterSelector' => $filterSelector,
Alexander Makarov committed
212
		];
213 214
	}

Qiang Xue committed
215
	/**
216
	 * Renders the data models for the grid view.
Qiang Xue committed
217 218 219
	 */
	public function renderItems()
	{
Alexander Makarov committed
220
		$content = array_filter([
Qiang Xue committed
221 222 223 224 225
			$this->renderCaption(),
			$this->renderColumnGroup(),
			$this->showHeader ? $this->renderTableHeader() : false,
			$this->showFooter ? $this->renderTableFooter() : false,
			$this->renderTableBody(),
Alexander Makarov committed
226
		]);
Qiang Xue committed
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
		return Html::tag('table', implode("\n", $content), $this->tableOptions);
	}

	public function renderCaption()
	{
		if (!empty($this->caption)) {
			return Html::tag('caption', $this->caption, $this->captionOptions);
		} else {
			return false;
		}
	}

	public function renderColumnGroup()
	{
		$requireColumnGroup = false;
		foreach ($this->columns as $column) {
243
			/** @var Column $column */
Qiang Xue committed
244 245 246 247 248 249
			if (!empty($column->options)) {
				$requireColumnGroup = true;
				break;
			}
		}
		if ($requireColumnGroup) {
Alexander Makarov committed
250
			$cols = [];
Qiang Xue committed
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
			foreach ($this->columns as $column) {
				$cols[] = Html::tag('col', '', $column->options);
			}
			return Html::tag('colgroup', implode("\n", $cols));
		} else {
			return false;
		}
	}

	/**
	 * Renders the table header.
	 * @return string the rendering result
	 */
	public function renderTableHeader()
	{
Alexander Makarov committed
266
		$cells = [];
Qiang Xue committed
267
		foreach ($this->columns as $column) {
268
			/** @var Column $column */
Qiang Xue committed
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
			$cells[] = $column->renderHeaderCell();
		}
		$content = implode('', $cells);
		if ($this->filterPosition == self::FILTER_POS_HEADER) {
			$content = $this->renderFilters() . $content;
		} elseif ($this->filterPosition == self::FILTER_POS_BODY) {
			$content .= $this->renderFilters();
		}
		return "<thead>\n" . Html::tag('tr', $content, $this->headerRowOptions) . "\n</thead>";
	}

	/**
	 * Renders the table footer.
	 * @return string the rendering result
	 */
	public function renderTableFooter()
	{
Alexander Makarov committed
286
		$cells = [];
Qiang Xue committed
287
		foreach ($this->columns as $column) {
288
			/** @var Column $column */
Qiang Xue committed
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
			$cells[] = $column->renderFooterCell();
		}
		$content = implode('', $cells);
		if ($this->filterPosition == self::FILTER_POS_FOOTER) {
			$content .= $this->renderFilters();
		}
		return "<tfoot>\n" . Html::tag('tr', $content, $this->footerRowOptions) . "\n</tfoot>";
	}

	/**
	 * Renders the filter.
	 */
	public function renderFilters()
	{
		if ($this->filterModel !== null) {
Alexander Makarov committed
304
			$cells = [];
Qiang Xue committed
305
			foreach ($this->columns as $column) {
306
				/** @var Column $column */
Qiang Xue committed
307 308
				$cells[] = $column->renderFilterCell();
			}
309
			return Html::tag('tr', implode('', $cells), $this->filterRowOptions);
Qiang Xue committed
310 311 312 313 314 315 316 317 318 319 320
		} else {
			return '';
		}
	}

	/**
	 * Renders the table body.
	 * @return string the rendering result
	 */
	public function renderTableBody()
	{
321
		$models = array_values($this->dataProvider->getModels());
Qiang Xue committed
322
		$keys = $this->dataProvider->getKeys();
Alexander Makarov committed
323
		$rows = [];
324
		foreach ($models as $index => $model) {
Qiang Xue committed
325 326
			$key = $keys[$index];
			if ($this->beforeRow !== null) {
327
				$row = call_user_func($this->beforeRow, $model, $key, $index, $this);
Qiang Xue committed
328 329 330 331 332
				if (!empty($row)) {
					$rows[] = $row;
				}
			}

333
			$rows[] = $this->renderTableRow($model, $key, $index);
Qiang Xue committed
334 335

			if ($this->afterRow !== null) {
336
				$row = call_user_func($this->afterRow, $model, $key, $index, $this);
Qiang Xue committed
337 338 339 340 341 342 343 344 345
				if (!empty($row)) {
					$rows[] = $row;
				}
			}
		}
		return "<tbody>\n" . implode("\n", $rows) . "\n</tbody>";
	}

	/**
346 347 348 349
	 * Renders a table row with the given data model and key.
	 * @param mixed $model the data model to be rendered
	 * @param mixed $key the key associated with the data model
	 * @param integer $index the zero-based index of the data model among the model array returned by [[dataProvider]].
Qiang Xue committed
350 351
	 * @return string the rendering result
	 */
352
	public function renderTableRow($model, $key, $index)
Qiang Xue committed
353
	{
Alexander Makarov committed
354
		$cells = [];
355
		/** @var Column $column */
Qiang Xue committed
356
		foreach ($this->columns as $column) {
357
			$cells[] = $column->renderDataCell($model, $index);
Qiang Xue committed
358 359
		}
		if ($this->rowOptions instanceof Closure) {
360
			$options = call_user_func($this->rowOptions, $model, $key, $index, $this);
Qiang Xue committed
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
		} else {
			$options = $this->rowOptions;
		}
		$options['data-key'] = $key;
		return Html::tag('tr', implode('', $cells), $options);
	}

	/**
	 * Creates column objects and initializes them.
	 */
	protected function initColumns()
	{
		if (empty($this->columns)) {
			$this->guessColumns();
		}
		foreach ($this->columns as $i => $column) {
			if (is_string($column)) {
				$column = $this->createDataColumn($column);
			} else {
Alexander Makarov committed
380
				$column = Yii::createObject(array_merge([
Qiang Xue committed
381
					'class' => $this->dataColumnClass ?: DataColumn::className(),
Qiang Xue committed
382
					'grid' => $this,
Alexander Makarov committed
383
				], $column));
Qiang Xue committed
384 385 386 387 388 389 390 391 392 393
			}
			if (!$column->visible) {
				unset($this->columns[$i]);
				continue;
			}
			$this->columns[$i] = $column;
		}
	}

	/**
394
	 * Creates a [[DataColumn]] object based on a string in the format of "attribute:format:label".
Qiang Xue committed
395 396 397 398 399 400
	 * @param string $text the column specification string
	 * @return DataColumn the column instance
	 * @throws InvalidConfigException if the column specification is invalid
	 */
	protected function createDataColumn($text)
	{
401
		if (!preg_match('/^([\w\.]+)(:(\w*))?(:(.*))?$/', $text, $matches)) {
402
			throw new InvalidConfigException('The column must be specified in the format of "attribute", "attribute:format" or "attribute:format:label');
Qiang Xue committed
403
		}
Alexander Makarov committed
404
		return Yii::createObject([
Qiang Xue committed
405
			'class' => $this->dataColumnClass ?: DataColumn::className(),
Qiang Xue committed
406 407
			'grid' => $this,
			'attribute' => $matches[1],
408
			'format' => isset($matches[3]) ? $matches[3] : 'text',
409
			'label' => isset($matches[5]) ? $matches[5] : null,
Alexander Makarov committed
410
		]);
Qiang Xue committed
411 412 413 414
	}

	protected function guessColumns()
	{
415 416 417 418
		$models = $this->dataProvider->getModels();
		$model = reset($models);
		if (is_array($model) || is_object($model)) {
			foreach ($model as $name => $value) {
Qiang Xue committed
419 420 421 422 423 424 425
				$this->columns[] = $name;
			}
		} else {
			throw new InvalidConfigException('Unable to generate columns from data.');
		}
	}
}