From 61c7ac9d8b1dbefe54e3128ecd906011aebe0085 Mon Sep 17 00:00:00 2001 From: Qiang Xue Date: Tue, 6 Aug 2013 13:38:29 -0400 Subject: [PATCH 01/59] Fixes #722. --- .../yii/console/controllers/MessageController.php | 2 +- framework/yii/messages/config.php | 45 ++++++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 framework/yii/messages/config.php diff --git a/framework/yii/console/controllers/MessageController.php b/framework/yii/console/controllers/MessageController.php index 5c85c21..306eb41 100644 --- a/framework/yii/console/controllers/MessageController.php +++ b/framework/yii/console/controllers/MessageController.php @@ -98,7 +98,7 @@ class MessageController extends Controller $messages = array(); foreach ($files as $file) { - $messages = array_merge($messages, $this->extractMessages($file, $config['translator'])); + $messages = array_merge_recursive($messages, $this->extractMessages($file, $config['translator'])); } foreach ($config['languages'] as $language) { diff --git a/framework/yii/messages/config.php b/framework/yii/messages/config.php new file mode 100644 index 0000000..e1c79ff --- /dev/null +++ b/framework/yii/messages/config.php @@ -0,0 +1,45 @@ + __DIR__ . '/..', + // string, required, root directory containing message translations. + 'messagePath' => __DIR__, + // array, required, list of language codes that the extracted messages + // should be translated to. For example, array('zh_cn', 'de'). + 'languages' => array('de'), + // string, the name of the function for translating messages. + // Defaults to 'Yii::t'. This is used as a mark to find the messages to be + // translated. You may use a string for single function name or an array for + // multiple function names. + 'translator' => 'Yii::t', + // boolean, whether to sort messages by keys when merging new messages + // with the existing ones. Defaults to false, which means the new (untranslated) + // messages will be separated from the old (translated) ones. + 'sort' => false, + // boolean, whether the message file should be overwritten with the merged messages + 'overwrite' => true, + // boolean, whether to remove messages that no longer appear in the source code. + // Defaults to false, which means each of these messages will be enclosed with a pair of '@@' marks. + 'removeUnused' => false, + // array, list of patterns that specify which files/directories should be processed. + // If empty or not set, all files/directories will be processed. + // A path matches a pattern if it contains the pattern string at its end. For example, + // '/a/b' will match all files and directories ending with '/a/b'; + // and the '.svn' will match all files and directories whose name ends with '.svn'. + // Note, the '/' characters in a pattern matches both '/' and '\'. + // If a file/directory matches both a pattern in "only" and "except", it will NOT be processed. + 'only' => array('.php'), + // array, list of patterns that specify which files/directories should NOT be processed. + // If empty or not set, all files/directories will be processed. + // Please refer to "only" for details about the patterns. + 'except' => array( + '.svn', + '.git', + '.gitignore', + '.gitkeep', + '.hgignore', + '.hgkeep', + '/messages', + ), +); From 7e5630b5589995da0e55a68bbd65b18f9ac80ac8 Mon Sep 17 00:00:00 2001 From: Qiang Xue Date: Tue, 6 Aug 2013 16:01:46 -0400 Subject: [PATCH 02/59] GridView WIP --- framework/yii/assets/yii.gridView.js | 78 +++++++++++ framework/yii/widgets/GridView.php | 28 ++-- framework/yii/widgets/ListViewBase.php | 4 - framework/yii/widgets/grid/CheckboxColumn.php | 186 +++++--------------------- framework/yii/widgets/grid/Column.php | 13 +- framework/yii/widgets/grid/GridViewAsset.php | 26 ++++ 6 files changed, 163 insertions(+), 172 deletions(-) create mode 100644 framework/yii/assets/yii.gridView.js create mode 100644 framework/yii/widgets/grid/GridViewAsset.php diff --git a/framework/yii/assets/yii.gridView.js b/framework/yii/assets/yii.gridView.js new file mode 100644 index 0000000..b07ece2 --- /dev/null +++ b/framework/yii/assets/yii.gridView.js @@ -0,0 +1,78 @@ +/** + * Yii GridView widget. + * + * This is the JavaScript widget used by the yii\grid\GridView widget. + * + * @link http://www.yiiframework.com/ + * @copyright Copyright (c) 2008 Yii Software LLC + * @license http://www.yiiframework.com/license/ + * @author Qiang Xue + * @since 2.0 + */ +(function ($) { + $.fn.yiiGridView = function (method) { + if (methods[method]) { + return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); + } else if (typeof method === 'object' || !method) { + return methods.init.apply(this, arguments); + } else { + $.error('Method ' + method + ' does not exist on jQuery.yiiGridView'); + return false; + } + }; + + var defaults = { + }; + + var methods = { + init: function (options) { + return this.each(function () { + var $e = $(this); + var settings = $.extend({}, defaults, options || {}); + $e.data('yiiGridView', { + settings: settings + }); + }); + }, + + setSelectionColumn: function (options) { + var $grid = $(this); + var data = $grid.data('yiiGridView'); + data.selectionColumn = options.name; + if (!options.multiple) { + return; + } + $grid.on('click.yiiGridView', "input[name='" + options.checkAll + "']", function () { + $grid.find("input[name='" + options.name + "']:enabled").prop('checked', this.checked); + }); + $grid.on('click.yiiGridView', "input[name='" + options.name + "']:enabled", function () { + var all = $grid.find("input[name='" + options.name + "']").length == $grid.find("input[name='" + options.name + "']:checked").length; + $grid.find("input[name='" + options.checkAll + "']").prop('checked', all); + }); + }, + + getSelectedRows: function () { + var $grid = $(this); + var data = $grid.data('yiiGridView'); + var keys = []; + if (data.selectionColumn) { + $grid.find("input[name='" + data.selectionColumn + "']:checked").each(function () { + keys.push($(this).parent().closest('tr').data('key')); + }); + } + return keys; + }, + + destroy: function () { + return this.each(function () { + $(window).unbind('.yiiGridView'); + $(this).removeData('yiiGridView'); + }); + }, + + data: function() { + return this.data('yiiGridView'); + } + }; +})(window.jQuery); + diff --git a/framework/yii/widgets/GridView.php b/framework/yii/widgets/GridView.php index cdfa782..a831ab8 100644 --- a/framework/yii/widgets/GridView.php +++ b/framework/yii/widgets/GridView.php @@ -15,6 +15,7 @@ use yii\base\Widget; use yii\db\ActiveRecord; use yii\helpers\Html; use yii\widgets\grid\DataColumn; +use yii\widgets\grid\GridViewAsset; /** * @author Qiang Xue @@ -26,7 +27,7 @@ class GridView extends ListViewBase const FILTER_POS_FOOTER = 'footer'; const FILTER_POS_BODY = 'body'; - public $dataColumnClass = 'yii\widgets\grid\DataColumn'; + public $dataColumnClass; public $caption; public $captionOptions = array(); public $tableOptions = array('class' => 'table table-striped table-bordered'); @@ -70,7 +71,7 @@ class GridView extends ListViewBase * - `{sorter}`: the sorter. See [[renderSorter()]]. * - `{pager}`: the pager. See [[renderPager()]]. */ - public $layout = "{summary}\n{pager}{items}\n{pager}"; + public $layout = "{items}\n{summary}\n{pager}"; public $emptyCell = ' '; /** * @var \yii\base\Model the model instance that keeps the user-entered filter data. When this property is set, @@ -107,11 +108,26 @@ class GridView extends ListViewBase if (!$this->formatter instanceof Formatter) { throw new InvalidConfigException('The "formatter" property must be either a Format object or a configuration array.'); } + if (!isset($this->options['id'])) { + $this->options['id'] = $this->getId(); + } $this->initColumns(); } /** + * Runs the widget. + */ + public function run() + { + $id = $this->options['id']; + $view = $this->getView(); + GridViewAsset::register($view); + $view->registerJs("jQuery('#$id').yiiGridView();"); + parent::run(); + } + + /** * Renders the data models for the grid view. */ public function renderItems() @@ -272,13 +288,12 @@ class GridView extends ListViewBase if (empty($this->columns)) { $this->guessColumns(); } - $id = $this->getId(); foreach ($this->columns as $i => $column) { if (is_string($column)) { $column = $this->createDataColumn($column); } else { $column = Yii::createObject(array_merge(array( - 'class' => $this->dataColumnClass, + 'class' => $this->dataColumnClass ?: DataColumn::className(), 'grid' => $this, ), $column)); } @@ -286,9 +301,6 @@ class GridView extends ListViewBase unset($this->columns[$i]); continue; } - if ($column->id === null) { - $column->id = $id . '_c' . $i; - } $this->columns[$i] = $column; } } @@ -305,7 +317,7 @@ class GridView extends ListViewBase throw new InvalidConfigException('The column must be specified in the format of "Attribute", "Attribute:Format" or "Attribute:Format:Header'); } return Yii::createObject(array( - 'class' => $this->dataColumnClass, + 'class' => $this->dataColumnClass ?: DataColumn::className(), 'grid' => $this, 'attribute' => $matches[1], 'format' => isset($matches[3]) ? $matches[3] : 'text', diff --git a/framework/yii/widgets/ListViewBase.php b/framework/yii/widgets/ListViewBase.php index fe318c4..6be704d 100644 --- a/framework/yii/widgets/ListViewBase.php +++ b/framework/yii/widgets/ListViewBase.php @@ -135,10 +135,6 @@ abstract class ListViewBase extends Widget $totalCount = $this->dataProvider->getTotalCount(); $begin = $pagination->getPage() * $pagination->pageSize + 1; $end = $begin + $count - 1; - if ($end > $totalCount) { - $end = $totalCount; - $begin = $end - $count + 1; - } $page = $pagination->getPage() + 1; $pageCount = $pagination->pageCount; if (($summaryContent = $this->summary) === null) { diff --git a/framework/yii/widgets/grid/CheckboxColumn.php b/framework/yii/widgets/grid/CheckboxColumn.php index e6bb327..5d1dc0c 100644 --- a/framework/yii/widgets/grid/CheckboxColumn.php +++ b/framework/yii/widgets/grid/CheckboxColumn.php @@ -7,185 +7,69 @@ namespace yii\widgets\grid; +use Closure; +use yii\base\InvalidConfigException; +use yii\helpers\Html; + /** * @author Qiang Xue * @since 2.0 */ class CheckboxColumn extends Column { - public $checked; - /** - * @var string a PHP expression that will be evaluated for every data cell and whose result will - * determine if checkbox for each data cell is disabled. In this expression, you can use the following variables: - *
    - *
  • $row the row number (zero-based)
  • - *
  • $data the data model for the row
  • - *
  • $this the column object
  • - *
- * The PHP expression will be evaluated using {@link evaluateExpression}. - * - * A PHP expression can be any PHP code that has a value. To learn more about what an expression is, - * please refer to the {@link http://www.php.net/manual/en/language.expressions.php php manual}. - * - * Note that expression result will overwrite value set with checkBoxHtmlOptions['disabled']. - * @since 1.1.13 - */ - public $disabled; - /** - * @var array the HTML options for the data cell tags. - */ - public $htmlOptions = array('class' => 'checkbox-column'); - /** - * @var array the HTML options for the header cell tag. - */ - public $headerHtmlOptions = array('class' => 'checkbox-column'); - /** - * @var array the HTML options for the footer cell tag. - */ - public $footerHtmlOptions = array('class' => 'checkbox-column'); - /** - * @var array the HTML options for the checkboxes. - */ - public $checkBoxHtmlOptions = array(); - /** - * @var integer the number of rows that can be checked. - * Possible values: - *
    - *
  • 0 - the state of the checkbox cannot be changed (read-only mode)
  • - *
  • 1 - only one row can be checked. Checking a checkbox has nothing to do with selecting the row
  • - *
  • 2 or more - multiple checkboxes can be checked. Checking a checkbox has nothing to do with selecting the row
  • - *
  • null - {@link CGridView::selectableRows} is used to control how many checkboxes can be checked. - * Checking a checkbox will also select the row.
  • - *
- * You may also call the JavaScript function $(gridID).yiiGridView('getChecked', columnID) - * to retrieve the key values of the checked rows. - * @since 1.1.6 - */ - public $selectableRows = null; - /** - * @var string the template to be used to control the layout of the header cell. - * The token "{item}" is recognized and it will be replaced with a "check all" checkbox. - * By default if in multiple checking mode, the header cell will display an additional checkbox, - * clicking on which will check or uncheck all of the checkboxes in the data cells. - * See {@link selectableRows} for more details. - * @since 1.1.11 - */ - public $headerTemplate = '{item}'; + public $name; + public $checkboxOptions = array(); + public $multiple = true; + - /** - * Initializes the column. - * This method registers necessary client script for the checkbox column. - */ public function init() { - if (isset($this->checkBoxHtmlOptions['name'])) { - $name = $this->checkBoxHtmlOptions['name']; - } else { - $name = $this->id; - if (substr($name, -2) !== '[]') { - $name .= '[]'; - } - $this->checkBoxHtmlOptions['name'] = $name; + parent::init(); + if (empty($this->name)) { + throw new InvalidConfigException('The "name" property must be set.'); } - $name = strtr($name, array('[' => "\\[", ']' => "\\]")); - - if ($this->selectableRows === null) { - if (isset($this->checkBoxHtmlOptions['class'])) { - $this->checkBoxHtmlOptions['class'] .= ' select-on-check'; - } else { - $this->checkBoxHtmlOptions['class'] = 'select-on-check'; - } - return; - } - - $cball = $cbcode = ''; - if ($this->selectableRows == 0) { - //.. read only - $cbcode = "return false;"; - } elseif ($this->selectableRows == 1) { - //.. only one can be checked, uncheck all other - $cbcode = "jQuery(\"input:not(#\"+this.id+\")[name='$name']\").prop('checked',false);"; - } elseif (strpos($this->headerTemplate, '{item}') !== false) { - //.. process check/uncheck all - $cball = <<id}_all',function() { - var checked=this.checked; - jQuery("input[name='$name']:enabled").each(function() {this.checked=checked;}); -}); - -CBALL; - $cbcode = "jQuery('#{$this->id}_all').prop('checked', jQuery(\"input[name='$name']\").length==jQuery(\"input[name='$name']:checked\").length);"; - } - - if ($cbcode !== '') { - $js = $cball; - $js .= <<getClientScript()->registerScript(__CLASS__ . '#' . $this->id, $js); + if (substr($this->name, -2) !== '[]') { + $this->name .= '[]'; } } /** * Renders the header cell content. - * This method will render a checkbox in the header when {@link selectableRows} is greater than 1 - * or in case {@link selectableRows} is null when {@link CGridView::selectableRows} is greater than 1. + * The default implementation simply renders {@link header}. + * This method may be overridden to customize the rendering of the header cell. + * @return string the rendering result */ protected function renderHeaderCellContent() { - if (trim($this->headerTemplate) === '') { - echo $this->grid->blankDisplay; - return; - } + $name = rtrim($this->name, '[]') . '_all'; + $id = $this->grid->options['id']; + $options = json_encode(array( + 'name' => $this->name, + 'multiple' => $this->multiple, + 'checkAll' => $name, + )); + $this->grid->getView()->registerJs("jQuery('#$id').yiiGridView('setSelectionColumn', $options);"); - $item = ''; - if ($this->selectableRows === null && $this->grid->selectableRows > 1) { - $item = CHtml::checkBox($this->id . '_all', false, array('class' => 'select-on-check-all')); - } elseif ($this->selectableRows > 1) { - $item = CHtml::checkBox($this->id . '_all', false); + if ($this->header !== null || !$this->multiple) { + return parent::renderHeaderCellContent(); } else { - ob_start(); - parent::renderHeaderCellContent(); - $item = ob_get_clean(); + return Html::checkBox($name, false, array('class' => 'select-on-check-all')); } - - echo strtr($this->headerTemplate, array( - '{item}' => $item, - )); } /** * Renders the data cell content. - * This method renders a checkbox in the data cell. - * @param integer $row the row number (zero-based) - * @param mixed $data the data associated with the row + * @param mixed $model the data model + * @param integer $index the zero-based index of the data model among the models array returned by [[dataProvider]]. + * @return string the rendering result */ - protected function renderDataCellContent($row, $data) + protected function renderDataCellContent($model, $index) { - if ($this->value !== null) { - $value = $this->evaluateExpression($this->value, array('data' => $data, 'row' => $row)); - } elseif ($this->name !== null) { - $value = CHtml::value($data, $this->name); + if ($this->checkboxOptions instanceof Closure) { + $options = call_user_func($this->checkboxOptions, $model, $index, $this); } else { - $value = $this->grid->dataProvider->keys[$row]; - } - - $checked = false; - if ($this->checked !== null) { - $checked = $this->evaluateExpression($this->checked, array('data' => $data, 'row' => $row)); - } - - $options = $this->checkBoxHtmlOptions; - if ($this->disabled !== null) { - $options['disabled'] = $this->evaluateExpression($this->disabled, array('data' => $data, 'row' => $row)); + $options = $this->checkboxOptions; } - - $name = $options['name']; - unset($options['name']); - $options['value'] = $value; - $options['id'] = $this->id . '_' . $row; - echo CHtml::checkBox($name, $checked, $options); + return Html::checkbox($this->name, !empty($options['checked']), $options); } } diff --git a/framework/yii/widgets/grid/Column.php b/framework/yii/widgets/grid/Column.php index 939904a..11e3d3d 100644 --- a/framework/yii/widgets/grid/Column.php +++ b/framework/yii/widgets/grid/Column.php @@ -20,11 +20,6 @@ use yii\widgets\GridView; class Column extends Object { /** - * @var string the ID of this column. This value should be unique among all grid view columns. - * If this is not set, it will be assigned one automatically. - */ - public $id; - /** * @var GridView the grid view object that owns this column. */ public $grid; @@ -49,7 +44,7 @@ class Column extends Object /** * @var array|\Closure */ - public $bodyOptions = array(); + public $contentOptions = array(); public $footerOptions = array(); /** * @var array the HTML attributes for the filter cell tag. @@ -81,10 +76,10 @@ class Column extends Object */ public function renderDataCell($model, $index) { - if ($this->bodyOptions instanceof Closure) { - $options = call_user_func($this->bodyOptions, $model, $index, $this); + if ($this->contentOptions instanceof Closure) { + $options = call_user_func($this->contentOptions, $model, $index, $this); } else { - $options = $this->bodyOptions; + $options = $this->contentOptions; } return Html::tag('td', $this->renderDataCellContent($model, $index), $options); } diff --git a/framework/yii/widgets/grid/GridViewAsset.php b/framework/yii/widgets/grid/GridViewAsset.php new file mode 100644 index 0000000..f0c2432 --- /dev/null +++ b/framework/yii/widgets/grid/GridViewAsset.php @@ -0,0 +1,26 @@ + + * @since 2.0 + */ +class GridViewAsset extends AssetBundle +{ + public $sourcePath = '@yii/assets'; + public $js = array( + 'yii.gridView.js', + ); + public $depends = array( + 'yii\web\YiiAsset', + ); +} From ca35bb05a8661bffcd6f574e55c6a35826dfa757 Mon Sep 17 00:00:00 2001 From: Qiang Xue Date: Tue, 6 Aug 2013 16:02:14 -0400 Subject: [PATCH 03/59] replaced attr with prop. --- framework/yii/assets/yii.activeForm.js | 12 ++++++------ framework/yii/widgets/ActiveForm.php | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/framework/yii/assets/yii.activeForm.js b/framework/yii/assets/yii.activeForm.js index 2b08d53..17ea8a7 100644 --- a/framework/yii/assets/yii.activeForm.js +++ b/framework/yii/assets/yii.activeForm.js @@ -83,7 +83,7 @@ var settings = $.extend({}, defaults, options || {}); if (settings.validationUrl === undefined) { - settings.validationUrl = $form.attr('action'); + settings.validationUrl = $form.prop('action'); } $.each(attributes, function (i) { attributes[i] = $.extend({value: getValue($form, this)}, attributeDefaults, this); @@ -291,13 +291,13 @@ // If the validation is triggered by form submission, ajax validation // should be done only when all inputs pass client validation var $button = data.submitObject, - extData = '&' + data.settings.ajaxVar + '=' + $form.attr('id'); - if ($button && $button.length && $button.attr('name')) { - extData += '&' + $button.attr('name') + '=' + $button.attr('value'); + extData = '&' + data.settings.ajaxVar + '=' + $form.prop('id'); + if ($button && $button.length && $button.prop('name')) { + extData += '&' + $button.prop('name') + '=' + $button.prop('value'); } $.ajax({ url: data.settings.validationUrl, - type: $form.attr('method'), + type: $form.prop('method'), data: $form.serialize() + extData, dataType: 'json', success: function (msgs) { @@ -380,7 +380,7 @@ var getValue = function ($form, attribute) { var $input = findInput($form, attribute); - var type = $input.attr('type'); + var type = $input.prop('type'); if (type === 'checkbox' || type === 'radio') { return $input.filter(':checked').val(); } else { diff --git a/framework/yii/widgets/ActiveForm.php b/framework/yii/widgets/ActiveForm.php index 1d4be89..fa04eb9 100644 --- a/framework/yii/widgets/ActiveForm.php +++ b/framework/yii/widgets/ActiveForm.php @@ -152,7 +152,7 @@ class ActiveForm extends Widget $this->options['id'] = $this->getId(); } if (!isset($this->fieldConfig['class'])) { - $this->fieldConfig['class'] = 'yii\widgets\ActiveField'; + $this->fieldConfig['class'] = ActiveField::className(); } echo Html::beginForm($this->action, $this->method, $this->options); } From b3b115146990c2518feb1d648f51e7a30a3ffd40 Mon Sep 17 00:00:00 2001 From: Qiang Xue Date: Tue, 6 Aug 2013 17:00:32 -0400 Subject: [PATCH 04/59] Finished draft implementation of GridView. --- framework/yii/base/Application.php | 2 +- framework/yii/classes.php | 8 +- framework/yii/grid/CheckboxColumn.php | 84 ++++++ framework/yii/grid/Column.php | 142 +++++++++ framework/yii/grid/DataColumn.php | 108 +++++++ framework/yii/grid/GridView.php | 406 ++++++++++++++++++++++++++ framework/yii/grid/GridViewAsset.php | 26 ++ framework/yii/grid/SerialColumn.php | 33 +++ framework/yii/widgets/GridView.php | 340 --------------------- framework/yii/widgets/grid/CheckboxColumn.php | 75 ----- framework/yii/widgets/grid/Column.php | 142 --------- framework/yii/widgets/grid/DataColumn.php | 94 ------ framework/yii/widgets/grid/GridViewAsset.php | 26 -- framework/yii/widgets/grid/SerialColumn.php | 32 -- 14 files changed, 804 insertions(+), 714 deletions(-) create mode 100644 framework/yii/grid/CheckboxColumn.php create mode 100644 framework/yii/grid/Column.php create mode 100644 framework/yii/grid/DataColumn.php create mode 100644 framework/yii/grid/GridView.php create mode 100644 framework/yii/grid/GridViewAsset.php create mode 100644 framework/yii/grid/SerialColumn.php delete mode 100644 framework/yii/widgets/GridView.php delete mode 100644 framework/yii/widgets/grid/CheckboxColumn.php delete mode 100644 framework/yii/widgets/grid/Column.php delete mode 100644 framework/yii/widgets/grid/DataColumn.php delete mode 100644 framework/yii/widgets/grid/GridViewAsset.php delete mode 100644 framework/yii/widgets/grid/SerialColumn.php diff --git a/framework/yii/base/Application.php b/framework/yii/base/Application.php index 687f1a3..aeba99b 100644 --- a/framework/yii/base/Application.php +++ b/framework/yii/base/Application.php @@ -169,7 +169,7 @@ abstract class Application extends Module public function registerErrorHandlers() { if (YII_ENABLE_ERROR_HANDLER) { - ini_set('display_errors', 0); + //ini_set('display_errors', 0); set_exception_handler(array($this, 'handleException')); set_error_handler(array($this, 'handleError'), error_reporting()); if ($this->memoryReserveSize > 0) { diff --git a/framework/yii/classes.php b/framework/yii/classes.php index a638dc0..367cc9a 100644 --- a/framework/yii/classes.php +++ b/framework/yii/classes.php @@ -230,10 +230,10 @@ return array( 'yii\widgets\ContentDecorator' => YII_PATH . '/widgets/ContentDecorator.php', 'yii\widgets\DetailView' => YII_PATH . '/widgets/DetailView.php', 'yii\widgets\FragmentCache' => YII_PATH . '/widgets/FragmentCache.php', - 'yii\widgets\grid\CheckboxColumn' => YII_PATH . '/widgets/grid/CheckboxColumn.php', - 'yii\widgets\grid\Column' => YII_PATH . '/widgets/grid/Column.php', - 'yii\widgets\grid\DataColumn' => YII_PATH . '/widgets/grid/DataColumn.php', - 'yii\widgets\GridView' => YII_PATH . '/widgets/GridView.php', + 'yii\grid\CheckboxColumn' => YII_PATH . '/grid/CheckboxColumn.php', + 'yii\grid\Column' => YII_PATH . '/grid/Column.php', + 'yii\grid\DataColumn' => YII_PATH . '/grid/DataColumn.php', + 'yii\grid\GridView' => YII_PATH . '/grid/GridView.php', 'yii\widgets\InputWidget' => YII_PATH . '/widgets/InputWidget.php', 'yii\widgets\LinkPager' => YII_PATH . '/widgets/LinkPager.php', 'yii\widgets\LinkSorter' => YII_PATH . '/widgets/LinkSorter.php', diff --git a/framework/yii/grid/CheckboxColumn.php b/framework/yii/grid/CheckboxColumn.php new file mode 100644 index 0000000..e9170f4 --- /dev/null +++ b/framework/yii/grid/CheckboxColumn.php @@ -0,0 +1,84 @@ + + * @since 2.0 + */ +class CheckboxColumn extends Column +{ + public $name = 'selection'; + public $checkboxOptions = array(); + public $multiple = true; + + + public function init() + { + parent::init(); + if (empty($this->name)) { + throw new InvalidConfigException('The "name" property must be set.'); + } + if (substr($this->name, -2) !== '[]') { + $this->name .= '[]'; + } + } + + /** + * Renders the header cell content. + * The default implementation simply renders {@link header}. + * This method may be overridden to customize the rendering of the header cell. + * @return string the rendering result + */ + protected function renderHeaderCellContent() + { + $name = rtrim($this->name, '[]') . '_all'; + $id = $this->grid->options['id']; + $options = json_encode(array( + 'name' => $this->name, + 'multiple' => $this->multiple, + 'checkAll' => $name, + )); + $this->grid->getView()->registerJs("jQuery('#$id').yiiGridView('setSelectionColumn', $options);"); + + if ($this->header !== null || !$this->multiple) { + return parent::renderHeaderCellContent(); + } else { + return Html::checkBox($name, false, array('class' => 'select-on-check-all')); + } + } + + /** + * Renders the data cell content. + * @param mixed $model the data model + * @param integer $index the zero-based index of the data model among the models array returned by [[dataProvider]]. + * @return string the rendering result + */ + protected function renderDataCellContent($model, $index) + { + if ($this->checkboxOptions instanceof Closure) { + $options = call_user_func($this->checkboxOptions, $model, $index, $this); + } else { + $options = $this->checkboxOptions; + } + return Html::checkbox($this->name, !empty($options['checked']), $options); + } +} diff --git a/framework/yii/grid/Column.php b/framework/yii/grid/Column.php new file mode 100644 index 0000000..b49f73e --- /dev/null +++ b/framework/yii/grid/Column.php @@ -0,0 +1,142 @@ + + * @since 2.0 + */ +class Column extends Object +{ + /** + * @var GridView the grid view object that owns this column. + */ + public $grid; + /** + * @var string the header cell content. Note that it will not be HTML-encoded. + */ + public $header; + /** + * @var string the footer cell content. Note that it will not be HTML-encoded. + */ + public $footer; + /** + * @var callable + */ + public $content; + /** + * @var boolean whether this column is visible. Defaults to true. + */ + public $visible = true; + public $options = array(); + public $headerOptions = array(); + /** + * @var array|\Closure + */ + public $contentOptions = array(); + public $footerOptions = array(); + /** + * @var array the HTML attributes for the filter cell tag. + */ + public $filterOptions=array(); + + + /** + * Renders the header cell. + */ + public function renderHeaderCell() + { + return Html::tag('th', $this->renderHeaderCellContent(), $this->headerOptions); + } + + /** + * Renders the footer cell. + */ + public function renderFooterCell() + { + return Html::tag('td', $this->renderFooterCellContent(), $this->footerOptions); + } + + /** + * Renders a data cell. + * @param mixed $model the data model being rendered + * @param integer $index the zero-based index of the data item among the item array returned by [[dataProvider]]. + * @return string the rendering result + */ + public function renderDataCell($model, $index) + { + if ($this->contentOptions instanceof Closure) { + $options = call_user_func($this->contentOptions, $model, $index, $this); + } else { + $options = $this->contentOptions; + } + return Html::tag('td', $this->renderDataCellContent($model, $index), $options); + } + + /** + * Renders the filter cell. + */ + public function renderFilterCell() + { + return Html::tag('td', $this->renderFilterCellContent(), $this->filterOptions); + } + + /** + * Renders the header cell content. + * The default implementation simply renders {@link header}. + * This method may be overridden to customize the rendering of the header cell. + * @return string the rendering result + */ + protected function renderHeaderCellContent() + { + return trim($this->header) !== '' ? $this->header : $this->grid->emptyCell; + } + + /** + * Renders the footer cell content. + * The default implementation simply renders {@link footer}. + * This method may be overridden to customize the rendering of the footer cell. + * @return string the rendering result + */ + protected function renderFooterCellContent() + { + return trim($this->footer) !== '' ? $this->footer : $this->grid->emptyCell; + } + + /** + * Renders the data cell content. + * @param mixed $model the data model + * @param integer $index the zero-based index of the data model among the models array returned by [[dataProvider]]. + * @return string the rendering result + */ + protected function renderDataCellContent($model, $index) + { + if ($this->content !== null) { + return call_user_func($this->content, $model, $index, $this); + } else { + return $this->grid->emptyCell; + } + } + + /** + * Renders the filter cell content. + * The default implementation simply renders a space. + * This method may be overridden to customize the rendering of the filter cell (if any). + * @return string the rendering result + */ + protected function renderFilterCellContent() + { + return $this->grid->emptyCell; + } +} diff --git a/framework/yii/grid/DataColumn.php b/framework/yii/grid/DataColumn.php new file mode 100644 index 0000000..29f6278 --- /dev/null +++ b/framework/yii/grid/DataColumn.php @@ -0,0 +1,108 @@ + + * @since 2.0 + */ +class DataColumn extends Column +{ + /** + * @var string the attribute name associated with this column. When neither [[content]] nor [[value]] + * is specified, the value of the specified attribute will be retrieved from each data model and displayed. + * + * Also, if [[header]] is not specified, the label associated with the attribute will be displayed. + */ + public $attribute; + /** + * @var \Closure an anonymous function that returns the value to be displayed for every data model. + * If this is not set, `$model[$attribute]` will be used to obtain the value. + */ + public $value; + /** + * @var string in which format should the value of each data model be displayed as (e.g. "text", "html"). + * Supported formats are determined by the [[GridView::formatter|formatter]] used by the [[GridView]]. + */ + public $format; + /** + * @var boolean whether to allow sorting by this column. If true and [[attribute]] is found in + * the sort definition of [[GridView::dataProvider]], then the header cell of this column + * will contain a link that may trigger the sorting when being clicked. + */ + public $enableSorting = true; + /** + * @var string|array|boolean the HTML code representing a filter input (e.g. a text field, a dropdown list) + * that is used for this data column. This property is effective only when [[GridView::filterModel]] is set. + * + * - If this property is not set, a text field will be generated as the filter input; + * - If this property is an array, a dropdown list will be generated that uses this property value as + * the list options. + * - If you don't want a filter for this data column, set this value to be false. + */ + public $filter; + + + protected function renderHeaderCellContent() + { + if ($this->attribute !== null && $this->header === null) { + $provider = $this->grid->dataProvider; + if ($this->enableSorting && ($sort = $provider->getSort()) !== false && $sort->hasAttribute($this->attribute)) { + return $sort->link($this->attribute); + } + $models = $provider->getModels(); + if (($model = reset($models)) instanceof Model) { + /** @var Model $model */ + return $model->getAttributeLabel($this->attribute); + } elseif ($provider instanceof ActiveDataProvider) { + if ($provider->query instanceof ActiveQuery) { + /** @var Model $model */ + $model = new $provider->query->modelClass; + return $model->getAttributeLabel($this->attribute); + } + } + return Inflector::camel2words($this->attribute); + } else { + return parent::renderHeaderCellContent(); + } + } + + protected function renderFilterCellContent() + { + if (is_string($this->filter)) { + return $this->filter; + } elseif ($this->filter !== false && $this->grid->filterModel instanceof Model && $this->attribute !== null) { + if (is_array($this->filter)) { + return Html::activeDropDownList($this->grid->filterModel, $this->attribute, $this->filter, array('prompt' => '')); + } else { + return Html::activeTextInput($this->grid->filterModel, $this->attribute); + } + } else { + return parent::renderFilterCellContent(); + } + } + + protected function renderDataCellContent($model, $index) + { + if ($this->value !== null) { + $value = call_user_func($this->value, $model, $index, $this); + } elseif ($this->content === null && $this->attribute !== null) { + $value = ArrayHelper::getValue($model, $this->attribute); + } else { + return parent::renderDataCellContent($model, $index); + } + return $this->grid->formatter->format($value, $this->format); + } +} diff --git a/framework/yii/grid/GridView.php b/framework/yii/grid/GridView.php new file mode 100644 index 0000000..9490f27 --- /dev/null +++ b/framework/yii/grid/GridView.php @@ -0,0 +1,406 @@ + + * @since 2.0 + */ +class GridView extends ListViewBase +{ + const FILTER_POS_HEADER = 'header'; + const FILTER_POS_FOOTER = 'footer'; + const FILTER_POS_BODY = 'body'; + + /** + * @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'. + */ + public $dataColumnClass; + /** + * @var string the caption of the grid table + * @see captionOptions + */ + public $caption; + /** + * @var array the HTML attributes for the caption element + * @see caption + */ + public $captionOptions = array(); + /** + * @var array the HTML attributes for the grid table element + */ + public $tableOptions = array('class' => 'table table-striped table-bordered'); + /** + * @var array the HTML attributes for the table header row + */ + public $headerRowOptions = array(); + /** + * @var array the HTML attributes for the table footer row + */ + public $footerRowOptions = array(); + /** + * @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 + */ + public $rowOptions = array(); + /** + * @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. + */ + public $beforeRow; + /** + * @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. + */ + public $afterRow; + /** + * @var boolean whether to show the header section of the grid table. + */ + public $showHeader = true; + /** + * @var boolean whether to show the footer section of the grid table. + */ + public $showFooter = false; + /** + * @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 + * for one particular grid column. For example, + * + * ~~~php + * array( + * array( + * 'class' => SerialColumn::className(), + * ), + * array( + * 'class' => DataColumn::className(), + * 'attribute' => 'name', + * 'format' => 'text', + * 'header' => 'Name', + * ), + * array( + * 'class' => CheckboxColumn::className(), + * ), + * ) + * ~~~ + * + * 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 + * which only contains "attribute", "format", and/or "header" options: `"attribute:format:header"`. + * For example, the above "name" column can also be specified as: `"name:text:Name"`. + * Both "format" and "header" are optional. They will take default values if absent. + */ + public $columns = array(); + /** + * @var string the layout that determines how different sections of the list view should be organized. + * The following tokens will be replaced with the corresponding section contents: + * + * - `{summary}`: the summary section. See [[renderSummary()]]. + * - `{items}`: the list items. See [[renderItems()]]. + * - `{sorter}`: the sorter. See [[renderSorter()]]. + * - `{pager}`: the pager. See [[renderPager()]]. + */ + public $layout = "{items}\n{summary}\n{pager}"; + public $emptyCell = ' '; + /** + * @var \yii\base\Model the model that keeps the user-entered filter data. When this property is set, + * 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. + * + * 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. + */ + public $filterModel; + /** + * @var string whether the filters should be displayed in the grid view. Valid values include: + * + * - [[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 + */ + public $filterRowOptions = array('class' => 'filters'); + + /** + * 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.'); + } + if (!isset($this->options['id'])) { + $this->options['id'] = $this->getId(); + } + + $this->initColumns(); + } + + /** + * Runs the widget. + */ + public function run() + { + $id = $this->options['id']; + $view = $this->getView(); + GridViewAsset::register($view); + $view->registerJs("jQuery('#$id').yiiGridView();"); + parent::run(); + } + + /** + * Renders the data models for the grid view. + */ + public function renderItems() + { + $content = array_filter(array( + $this->renderCaption(), + $this->renderColumnGroup(), + $this->showHeader ? $this->renderTableHeader() : false, + $this->showFooter ? $this->renderTableFooter() : false, + $this->renderTableBody(), + )); + 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) { + /** @var Column $column */ + if (!empty($column->options)) { + $requireColumnGroup = true; + break; + } + } + if ($requireColumnGroup) { + $cols = array(); + 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() + { + $cells = array(); + foreach ($this->columns as $column) { + /** @var Column $column */ + $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 "\n" . Html::tag('tr', $content, $this->headerRowOptions) . "\n"; + } + + /** + * Renders the table footer. + * @return string the rendering result + */ + public function renderTableFooter() + { + $cells = array(); + foreach ($this->columns as $column) { + /** @var Column $column */ + $cells[] = $column->renderFooterCell(); + } + $content = implode('', $cells); + if ($this->filterPosition == self::FILTER_POS_FOOTER) { + $content .= $this->renderFilters(); + } + return "\n" . Html::tag('tr', $content, $this->footerRowOptions) . "\n"; + } + + /** + * Renders the filter. + */ + public function renderFilters() + { + if ($this->filterModel !== null) { + $cells = array(); + foreach ($this->columns as $column) { + /** @var Column $column */ + $cells[] = $column->renderFilterCell(); + } + return Html::tag('tr', implode('', $cells), $this->filterRowOptions); + } else { + return ''; + } + } + + /** + * Renders the table body. + * @return string the rendering result + */ + public function renderTableBody() + { + $models = array_values($this->dataProvider->getModels()); + $keys = $this->dataProvider->getKeys(); + $rows = array(); + foreach ($models as $index => $model) { + $key = $keys[$index]; + if ($this->beforeRow !== null) { + $row = call_user_func($this->beforeRow, $model, $key, $index, $this); + if (!empty($row)) { + $rows[] = $row; + } + } + + $rows[] = $this->renderTableRow($model, $key, $index); + + if ($this->afterRow !== null) { + $row = call_user_func($this->afterRow, $model, $key, $index, $this); + if (!empty($row)) { + $rows[] = $row; + } + } + } + return "\n" . implode("\n", $rows) . "\n"; + } + + /** + * 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]]. + * @return string the rendering result + */ + public function renderTableRow($model, $key, $index) + { + $cells = array(); + /** @var Column $column */ + foreach ($this->columns as $column) { + $cells[] = $column->renderDataCell($model, $index); + } + if ($this->rowOptions instanceof Closure) { + $options = call_user_func($this->rowOptions, $model, $key, $index, $this); + } 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 { + $column = Yii::createObject(array_merge(array( + 'class' => $this->dataColumnClass ?: DataColumn::className(), + 'grid' => $this, + ), $column)); + } + if (!$column->visible) { + unset($this->columns[$i]); + continue; + } + $this->columns[$i] = $column; + } + } + + /** + * Creates a [[DataColumn]] object based on a string in the format of "attribute:format:header". + * @param string $text the column specification string + * @return DataColumn the column instance + * @throws InvalidConfigException if the column specification is invalid + */ + protected function createDataColumn($text) + { + if (!preg_match('/^([\w\.]+)(:(\w*))?(:(.*))?$/', $text, $matches)) { + throw new InvalidConfigException('The column must be specified in the format of "attribute", "attribute:format" or "attribute:format:header'); + } + return Yii::createObject(array( + 'class' => $this->dataColumnClass ?: DataColumn::className(), + 'grid' => $this, + 'attribute' => $matches[1], + 'format' => isset($matches[3]) ? $matches[3] : 'text', + 'header' => isset($matches[5]) ? $matches[5] : null, + )); + } + + protected function guessColumns() + { + $models = $this->dataProvider->getModels(); + $model = reset($models); + if (is_array($model) || is_object($model)) { + foreach ($model as $name => $value) { + $this->columns[] = $name; + } + } else { + throw new InvalidConfigException('Unable to generate columns from data.'); + } + } +} diff --git a/framework/yii/grid/GridViewAsset.php b/framework/yii/grid/GridViewAsset.php new file mode 100644 index 0000000..decf674 --- /dev/null +++ b/framework/yii/grid/GridViewAsset.php @@ -0,0 +1,26 @@ + + * @since 2.0 + */ +class GridViewAsset extends AssetBundle +{ + public $sourcePath = '@yii/assets'; + public $js = array( + 'yii.gridView.js', + ); + public $depends = array( + 'yii\web\YiiAsset', + ); +} diff --git a/framework/yii/grid/SerialColumn.php b/framework/yii/grid/SerialColumn.php new file mode 100644 index 0000000..3a5e21b --- /dev/null +++ b/framework/yii/grid/SerialColumn.php @@ -0,0 +1,33 @@ + + * @since 2.0 + */ +class SerialColumn extends Column +{ + /** + * Renders the data cell content. + * @param mixed $model the data model + * @param integer $index the zero-based index of the data model among the models array returned by [[dataProvider]]. + * @return string the rendering result + */ + protected function renderDataCellContent($model, $index) + { + $pagination = $this->grid->dataProvider->getPagination(); + if ($pagination !== false) { + return $pagination->getOffset() + $index + 1; + } else { + return $index + 1; + } + } +} diff --git a/framework/yii/widgets/GridView.php b/framework/yii/widgets/GridView.php deleted file mode 100644 index a831ab8..0000000 --- a/framework/yii/widgets/GridView.php +++ /dev/null @@ -1,340 +0,0 @@ - - * @since 2.0 - */ -class GridView extends ListViewBase -{ - const FILTER_POS_HEADER = 'header'; - const FILTER_POS_FOOTER = 'footer'; - const FILTER_POS_BODY = 'body'; - - public $dataColumnClass; - public $caption; - public $captionOptions = array(); - public $tableOptions = array('class' => 'table table-striped table-bordered'); - public $headerRowOptions = array(); - public $footerRowOptions = array(); - public $beforeRow; - public $afterRow; - public $showHeader = true; - public $showFooter = false; - /** - * @var array|Closure - */ - public $rowOptions = array(); - /** - * @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 - * for one particular grid column which can be either a string or an array. - * - * When a column is specified as a string, it should be in the format of "name:type:header", - * where "type" and "header" are optional. A {@link CDataColumn} instance will be created in this case, - * whose {@link CDataColumn::name}, {@link CDataColumn::type} and {@link CDataColumn::header} - * properties will be initialized accordingly. - * - * When a column is specified as an array, it will be used to create a grid column instance, where - * the 'class' element specifies the column class name (defaults to {@link CDataColumn} if absent). - * Currently, these official column classes are provided: {@link CDataColumn}, - * {@link CLinkColumn}, {@link CButtonColumn} and {@link CCheckBoxColumn}. - */ - public $columns = array(); - /** - * @var string the layout that determines how different sections of the list view should be organized. - * The following tokens will be replaced with the corresponding section contents: - * - * - `{summary}`: the summary section. See [[renderSummary()]]. - * - `{items}`: the list items. See [[renderItems()]]. - * - `{sorter}`: the sorter. See [[renderSorter()]]. - * - `{pager}`: the pager. See [[renderPager()]]. - */ - public $layout = "{items}\n{summary}\n{pager}"; - public $emptyCell = ' '; - /** - * @var \yii\base\Model the model instance that keeps the user-entered filter data. When this property is set, - * 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. - * Note that in order to show an input field for filtering, a column must have its {@link CDataColumn::name} - * property set or have {@link CDataColumn::filter} as the HTML code for the input field. - * When this property is not set (null) the filtering is disabled. - */ - public $filterModel; - /** - * @var string whether the filters should be displayed in the grid view. Valid values include: - *
    - *
  • header: the filters will be displayed on top of each column's header cell.
  • - *
  • body: the filters will be displayed right below each column's header cell.
  • - *
  • footer: the filters will be displayed below each column's footer cell.
  • - *
- */ - public $filterPosition = 'body'; - public $filterOptions = array('class' => 'filters'); - - /** - * 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.'); - } - if (!isset($this->options['id'])) { - $this->options['id'] = $this->getId(); - } - - $this->initColumns(); - } - - /** - * Runs the widget. - */ - public function run() - { - $id = $this->options['id']; - $view = $this->getView(); - GridViewAsset::register($view); - $view->registerJs("jQuery('#$id').yiiGridView();"); - parent::run(); - } - - /** - * Renders the data models for the grid view. - */ - public function renderItems() - { - $content = array_filter(array( - $this->renderCaption(), - $this->renderColumnGroup(), - $this->showHeader ? $this->renderTableHeader() : false, - $this->showFooter ? $this->renderTableFooter() : false, - $this->renderTableBody(), - )); - 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) { - /** @var \yii\widgets\grid\Column $column */ - if (!empty($column->options)) { - $requireColumnGroup = true; - break; - } - } - if ($requireColumnGroup) { - $cols = array(); - 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() - { - $cells = array(); - foreach ($this->columns as $column) { - /** @var \yii\widgets\grid\Column $column */ - $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 "\n" . Html::tag('tr', $content, $this->headerRowOptions) . "\n"; - } - - /** - * Renders the table footer. - * @return string the rendering result - */ - public function renderTableFooter() - { - $cells = array(); - foreach ($this->columns as $column) { - /** @var \yii\widgets\grid\Column $column */ - $cells[] = $column->renderFooterCell(); - } - $content = implode('', $cells); - if ($this->filterPosition == self::FILTER_POS_FOOTER) { - $content .= $this->renderFilters(); - } - return "\n" . Html::tag('tr', $content, $this->footerRowOptions) . "\n"; - } - - /** - * Renders the filter. - */ - public function renderFilters() - { - if ($this->filterModel !== null) { - $cells = array(); - foreach ($this->columns as $column) { - /** @var \yii\widgets\grid\Column $column */ - $cells[] = $column->renderFilterCell(); - } - return Html::tag('tr', implode('', $cells), $this->filterOptions); - } else { - return ''; - } - } - - /** - * Renders the table body. - * @return string the rendering result - */ - public function renderTableBody() - { - $models = array_values($this->dataProvider->getModels()); - $keys = $this->dataProvider->getKeys(); - $rows = array(); - foreach ($models as $index => $model) { - $key = $keys[$index]; - if ($this->beforeRow !== null) { - $row = call_user_func($this->beforeRow, $model, $key, $index); - if (!empty($row)) { - $rows[] = $row; - } - } - - $rows[] = $this->renderTableRow($model, $key, $index); - - if ($this->afterRow !== null) { - $row = call_user_func($this->afterRow, $model, $key, $index); - if (!empty($row)) { - $rows[] = $row; - } - } - } - return "\n" . implode("\n", $rows) . "\n"; - } - - /** - * 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]]. - * @return string the rendering result - */ - public function renderTableRow($model, $key, $index) - { - $cells = array(); - /** @var \yii\widgets\grid\Column $column */ - foreach ($this->columns as $column) { - $cells[] = $column->renderDataCell($model, $index); - } - if ($this->rowOptions instanceof Closure) { - $options = call_user_func($this->rowOptions, $model, $key, $index); - } 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 { - $column = Yii::createObject(array_merge(array( - 'class' => $this->dataColumnClass ?: DataColumn::className(), - 'grid' => $this, - ), $column)); - } - if (!$column->visible) { - unset($this->columns[$i]); - continue; - } - $this->columns[$i] = $column; - } - } - - /** - * Creates a {@link CDataColumn} based on a shortcut column specification string. - * @param string $text the column specification string - * @return DataColumn the column instance - * @throws InvalidConfigException if the column specification is invalid - */ - protected function createDataColumn($text) - { - if (!preg_match('/^([\w\.]+)(:(\w*))?(:(.*))?$/', $text, $matches)) { - throw new InvalidConfigException('The column must be specified in the format of "Attribute", "Attribute:Format" or "Attribute:Format:Header'); - } - return Yii::createObject(array( - 'class' => $this->dataColumnClass ?: DataColumn::className(), - 'grid' => $this, - 'attribute' => $matches[1], - 'format' => isset($matches[3]) ? $matches[3] : 'text', - 'header' => isset($matches[5]) ? $matches[5] : null, - )); - } - - protected function guessColumns() - { - $models = $this->dataProvider->getModels(); - $model = reset($models); - if (is_array($model) || is_object($model)) { - foreach ($model as $name => $value) { - $this->columns[] = $name; - } - } else { - throw new InvalidConfigException('Unable to generate columns from data.'); - } - } -} diff --git a/framework/yii/widgets/grid/CheckboxColumn.php b/framework/yii/widgets/grid/CheckboxColumn.php deleted file mode 100644 index 5d1dc0c..0000000 --- a/framework/yii/widgets/grid/CheckboxColumn.php +++ /dev/null @@ -1,75 +0,0 @@ - - * @since 2.0 - */ -class CheckboxColumn extends Column -{ - public $name; - public $checkboxOptions = array(); - public $multiple = true; - - - public function init() - { - parent::init(); - if (empty($this->name)) { - throw new InvalidConfigException('The "name" property must be set.'); - } - if (substr($this->name, -2) !== '[]') { - $this->name .= '[]'; - } - } - - /** - * Renders the header cell content. - * The default implementation simply renders {@link header}. - * This method may be overridden to customize the rendering of the header cell. - * @return string the rendering result - */ - protected function renderHeaderCellContent() - { - $name = rtrim($this->name, '[]') . '_all'; - $id = $this->grid->options['id']; - $options = json_encode(array( - 'name' => $this->name, - 'multiple' => $this->multiple, - 'checkAll' => $name, - )); - $this->grid->getView()->registerJs("jQuery('#$id').yiiGridView('setSelectionColumn', $options);"); - - if ($this->header !== null || !$this->multiple) { - return parent::renderHeaderCellContent(); - } else { - return Html::checkBox($name, false, array('class' => 'select-on-check-all')); - } - } - - /** - * Renders the data cell content. - * @param mixed $model the data model - * @param integer $index the zero-based index of the data model among the models array returned by [[dataProvider]]. - * @return string the rendering result - */ - protected function renderDataCellContent($model, $index) - { - if ($this->checkboxOptions instanceof Closure) { - $options = call_user_func($this->checkboxOptions, $model, $index, $this); - } else { - $options = $this->checkboxOptions; - } - return Html::checkbox($this->name, !empty($options['checked']), $options); - } -} diff --git a/framework/yii/widgets/grid/Column.php b/framework/yii/widgets/grid/Column.php deleted file mode 100644 index 11e3d3d..0000000 --- a/framework/yii/widgets/grid/Column.php +++ /dev/null @@ -1,142 +0,0 @@ - - * @since 2.0 - */ -class Column extends Object -{ - /** - * @var GridView the grid view object that owns this column. - */ - public $grid; - /** - * @var string the header cell content. Note that it will not be HTML-encoded. - */ - public $header; - /** - * @var string the footer cell content. Note that it will not be HTML-encoded. - */ - public $footer; - /** - * @var callable - */ - public $content; - /** - * @var boolean whether this column is visible. Defaults to true. - */ - public $visible = true; - public $options = array(); - public $headerOptions = array(); - /** - * @var array|\Closure - */ - public $contentOptions = array(); - public $footerOptions = array(); - /** - * @var array the HTML attributes for the filter cell tag. - */ - public $filterOptions=array(); - - - /** - * Renders the header cell. - */ - public function renderHeaderCell() - { - return Html::tag('th', $this->renderHeaderCellContent(), $this->headerOptions); - } - - /** - * Renders the footer cell. - */ - public function renderFooterCell() - { - return Html::tag('td', $this->renderFooterCellContent(), $this->footerOptions); - } - - /** - * Renders a data cell. - * @param mixed $model the data model being rendered - * @param integer $index the zero-based index of the data item among the item array returned by [[dataProvider]]. - * @return string the rendering result - */ - public function renderDataCell($model, $index) - { - if ($this->contentOptions instanceof Closure) { - $options = call_user_func($this->contentOptions, $model, $index, $this); - } else { - $options = $this->contentOptions; - } - return Html::tag('td', $this->renderDataCellContent($model, $index), $options); - } - - /** - * Renders the filter cell. - */ - public function renderFilterCell() - { - return Html::tag('td', $this->renderFilterCellContent(), $this->filterOptions); - } - - /** - * Renders the header cell content. - * The default implementation simply renders {@link header}. - * This method may be overridden to customize the rendering of the header cell. - * @return string the rendering result - */ - protected function renderHeaderCellContent() - { - return trim($this->header) !== '' ? $this->header : $this->grid->emptyCell; - } - - /** - * Renders the footer cell content. - * The default implementation simply renders {@link footer}. - * This method may be overridden to customize the rendering of the footer cell. - * @return string the rendering result - */ - protected function renderFooterCellContent() - { - return trim($this->footer) !== '' ? $this->footer : $this->grid->emptyCell; - } - - /** - * Renders the data cell content. - * @param mixed $model the data model - * @param integer $index the zero-based index of the data model among the models array returned by [[dataProvider]]. - * @return string the rendering result - */ - protected function renderDataCellContent($model, $index) - { - if ($this->content !== null) { - return call_user_func($this->content, $model, $index, $this); - } else { - return $this->grid->emptyCell; - } - } - - /** - * Renders the filter cell content. - * The default implementation simply renders a space. - * This method may be overridden to customize the rendering of the filter cell (if any). - * @return string the rendering result - */ - protected function renderFilterCellContent() - { - return $this->grid->emptyCell; - } -} diff --git a/framework/yii/widgets/grid/DataColumn.php b/framework/yii/widgets/grid/DataColumn.php deleted file mode 100644 index ac65c4c..0000000 --- a/framework/yii/widgets/grid/DataColumn.php +++ /dev/null @@ -1,94 +0,0 @@ - - * @since 2.0 - */ -class DataColumn extends Column -{ - public $attribute; - public $value; - public $format; - /** - * @var boolean whether to allow sorting by this column. If true and [[attribute]] is found in - * the sort definition of [[GridView::dataProvider]], then the header cell of this column - * will contain a link that may trigger the sorting when being clicked. - */ - public $enableSorting = true; - /** - * @var string|array|boolean the HTML code representing a filter input (eg a text field, a dropdown list) - * that is used for this data column. This property is effective only when - * {@link CGridView::filter} is set. - * If this property is not set, a text field will be generated as the filter input; - * If this property is an array, a dropdown list will be generated that uses this property value as - * the list options. - * If you don't want a filter for this data column, set this value to false. - */ - public $filter; - - - protected function renderHeaderCellContent() - { - if ($this->attribute !== null && $this->header === null) { - $provider = $this->grid->dataProvider; - if ($this->enableSorting && ($sort = $provider->getSort()) !== false && $sort->hasAttribute($this->attribute)) { - return $sort->link($this->attribute); - } - $models = $provider->getModels(); - if (($model = reset($models)) instanceof Model) { - /** @var Model $model */ - return $model->getAttributeLabel($this->attribute); - } elseif ($provider instanceof ActiveDataProvider) { - if ($provider->query instanceof ActiveQuery) { - /** @var Model $model */ - $model = new $provider->query->modelClass; - return $model->getAttributeLabel($this->attribute); - } - } - return Inflector::camel2words($this->attribute); - } else { - return parent::renderHeaderCellContent(); - } - } - - protected function renderFilterCellContent() - { - if (is_string($this->filter)) { - return $this->filter; - } elseif ($this->filter !== false && $this->grid->filterModel instanceof Model && $this->attribute !== null) { - if (is_array($this->filter)) { - return Html::activeDropDownList($this->grid->filterModel, $this->attribute, $this->filter, array('prompt' => '')); - } else { - return Html::activeTextInput($this->grid->filterModel, $this->attribute); - } - } else { - return parent::renderFilterCellContent(); - } - } - - protected function renderDataCellContent($model, $index) - { - if ($this->value !== null) { - $value = call_user_func($this->value, $model, $index, $this); - } elseif ($this->content === null && $this->attribute !== null) { - $value = ArrayHelper::getValue($model, $this->attribute); - } else { - return parent::renderDataCellContent($model, $index); - } - return $this->grid->formatter->format($value, $this->format); - } -} diff --git a/framework/yii/widgets/grid/GridViewAsset.php b/framework/yii/widgets/grid/GridViewAsset.php deleted file mode 100644 index f0c2432..0000000 --- a/framework/yii/widgets/grid/GridViewAsset.php +++ /dev/null @@ -1,26 +0,0 @@ - - * @since 2.0 - */ -class GridViewAsset extends AssetBundle -{ - public $sourcePath = '@yii/assets'; - public $js = array( - 'yii.gridView.js', - ); - public $depends = array( - 'yii\web\YiiAsset', - ); -} diff --git a/framework/yii/widgets/grid/SerialColumn.php b/framework/yii/widgets/grid/SerialColumn.php deleted file mode 100644 index b9b78a7..0000000 --- a/framework/yii/widgets/grid/SerialColumn.php +++ /dev/null @@ -1,32 +0,0 @@ - - * @since 2.0 - */ -class SerialColumn extends Column -{ - /** - * Renders the data cell content. - * @param mixed $model the data model - * @param integer $index the zero-based index of the data model among the models array returned by [[dataProvider]]. - * @return string the rendering result - */ - protected function renderDataCellContent($model, $index) - { - $pagination = $this->grid->dataProvider->getPagination(); - if ($pagination !== false) { - return $pagination->getOffset() + $index + 1; - } else { - return $index + 1; - } - } -} From 588f9fd57579435482a5f6eeda792ed0049e8f4d Mon Sep 17 00:00:00 2001 From: Jani Mikkonen Date: Wed, 7 Aug 2013 16:41:27 +0300 Subject: [PATCH 05/59] Add more readme badges. Fix #726. --- README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 52af522..1cd0121 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,10 @@ If you are looking for a production-ready PHP framework, please use Yii 2.0 is still under heavy development. We may make significant changes without prior notices. **Yii 2.0 is not ready for production use yet.** -[![Build Status](https://secure.travis-ci.org/yiisoft/yii2.png)](http://travis-ci.org/yiisoft/yii2) [![Dependency Status](https://www.versioneye.com/php/yiisoft:yii2/dev-master/badge.png)](https://www.versioneye.com/php/yiisoft:yii2/dev-master) +[![Latest Stable Version](https://poser.pugx.org/yiisoft/yii2/v/stable.png)](https://packagist.org/packages/yiisoft/yii2) +[![Total Downloads](https://poser.pugx.org/yiisoft/yii2/downloads.png)](https://packagist.org/packages/yiisoft/yii2) +[![Build Status](https://secure.travis-ci.org/yiisoft/yii2.png)](http://travis-ci.org/yiisoft/yii2) +[![Dependency Status](https://www.versioneye.com/php/yiisoft:yii2/dev-master/badge.png)](https://www.versioneye.com/php/yiisoft:yii2/dev-master) DIRECTORY STRUCTURE From 4727ac8f1d61a538f9cafa0c2350f8a5618e8ff3 Mon Sep 17 00:00:00 2001 From: Qiang Xue Date: Wed, 7 Aug 2013 22:22:23 -0400 Subject: [PATCH 06/59] Refactored the feature of transactional operations. --- framework/yii/base/Model.php | 18 ++++------ framework/yii/db/ActiveRecord.php | 73 ++++++++++++++++++++++++++++----------- 2 files changed, 59 insertions(+), 32 deletions(-) diff --git a/framework/yii/base/Model.php b/framework/yii/base/Model.php index bb0f4b1..f1f1072 100644 --- a/framework/yii/base/Model.php +++ b/framework/yii/base/Model.php @@ -8,8 +8,11 @@ namespace yii\base; use Yii; +use ArrayAccess; use ArrayObject; use ArrayIterator; +use ReflectionClass; +use IteratorAggregate; use yii\helpers\Inflector; use yii\validators\RequiredValidator; use yii\validators\Validator; @@ -42,7 +45,7 @@ use yii\validators\Validator; * @author Qiang Xue * @since 2.0 */ -class Model extends Component implements \IteratorAggregate, \ArrayAccess +class Model extends Component implements IteratorAggregate, ArrayAccess { /** * @event ModelEvent an event raised at the beginning of [[validate()]]. You may set @@ -184,7 +187,7 @@ class Model extends Component implements \IteratorAggregate, \ArrayAccess */ public function formName() { - $reflector = new \ReflectionClass($this); + $reflector = new ReflectionClass($this); return $reflector->getShortName(); } @@ -196,7 +199,7 @@ class Model extends Component implements \IteratorAggregate, \ArrayAccess */ public function attributes() { - $class = new \ReflectionClass($this); + $class = new ReflectionClass($this); $names = array(); foreach ($class->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) { $name = $property->getName(); @@ -608,9 +611,6 @@ class Model extends Component implements \IteratorAggregate, \ArrayAccess return array(); } $attributes = array(); - if (isset($scenarios[$scenario]['attributes']) && is_array($scenarios[$scenario]['attributes'])) { - $scenarios[$scenario] = $scenarios[$scenario]['attributes']; - } foreach ($scenarios[$scenario] as $attribute) { if ($attribute[0] !== '!') { $attributes[] = $attribute; @@ -630,11 +630,7 @@ class Model extends Component implements \IteratorAggregate, \ArrayAccess if (!isset($scenarios[$scenario])) { return array(); } - if (isset($scenarios[$scenario]['attributes']) && is_array($scenarios[$scenario]['attributes'])) { - $attributes = $scenarios[$scenario]['attributes']; - } else { - $attributes = $scenarios[$scenario]; - } + $attributes = $scenarios[$scenario]; foreach ($attributes as $i => $attribute) { if ($attribute[0] === '!') { $attributes[$i] = substr($attribute, 1); diff --git a/framework/yii/db/ActiveRecord.php b/framework/yii/db/ActiveRecord.php index 6e42106..d385bed 100644 --- a/framework/yii/db/ActiveRecord.php +++ b/framework/yii/db/ActiveRecord.php @@ -72,20 +72,22 @@ class ActiveRecord extends Model const EVENT_AFTER_DELETE = 'afterDelete'; /** - * Represents insert ActiveRecord operation. This constant is used for specifying set of atomic operations - * for particular scenario in the [[scenarios()]] method. + * The insert operation. This is mainly used when overriding [[transactions()]] to specify which operations are transactional. */ - const OP_INSERT = 'insert'; + const OP_INSERT = 0x01; /** - * Represents update ActiveRecord operation. This constant is used for specifying set of atomic operations - * for particular scenario in the [[scenarios()]] method. + * The update operation. This is mainly used when overriding [[transactions()]] to specify which operations are transactional. */ - const OP_UPDATE = 'update'; + const OP_UPDATE = 0x02; /** - * Represents delete ActiveRecord operation. This constant is used for specifying set of atomic operations - * for particular scenario in the [[scenarios()]] method. + * The delete operation. This is mainly used when overriding [[transactions()]] to specify which operations are transactional. */ - const OP_DELETE = 'delete'; + const OP_DELETE = 0x04; + /** + * All three operations: insert, update, delete. + * This is a shortcut of the expression: OP_INSERT | OP_UPDATE | OP_DELETE. + */ + const OP_ALL = 0x07; /** * @var array attribute values indexed by attribute names @@ -331,6 +333,38 @@ class ActiveRecord extends Model } /** + * Declares which DB operations should be performed within a transaction in different scenarios. + * The supported DB operations are: [[OP_INSERT]], [[OP_UPDATE]] and [[OP_DELETE]], + * which correspond to the [[insert()]], [[update()]] and [[delete()]] methods, respectively. + * By default, these methods are NOT enclosed in a DB transaction. + * + * In some scenarios, to ensure data consistency, you may want to enclose some or all of them + * in transactions. You can do so by overriding this method and returning the operations + * that need to be transactional. For example, + * + * ~~~ + * return array( + * 'admin' => self::OP_INSERT, + * 'api' => self::OP_INSERT | self::OP_UPDATE | self::OP_DELETE, + * // the above is equivalent to the following: + * // 'api' => self::OP_ALL, + * + * ); + * ~~~ + * + * The above declaration specifies that in the "admin" scenario, the insert operation ([[insert()]]) + * should be done in a transaction; and in the "api" scenario, all the operations should be done + * in a transaction. + * + * @return array the declarations of transactional operations. The array keys are scenarios names, + * and the array values are the corresponding transaction operations. + */ + public function transactions() + { + return array(); + } + + /** * PHP getter magic method. * This method is overridden so that attributes and related objects can be accessed like properties. * @param string $name property name @@ -712,7 +746,7 @@ class ActiveRecord extends Model return false; } $db = static::getDb(); - $transaction = $this->isOperationAtomic(self::OP_INSERT) && $db->getTransaction() === null ? $db->beginTransaction() : null; + $transaction = $this->isTransactional(self::OP_INSERT) && $db->getTransaction() === null ? $db->beginTransaction() : null; try { $result = $this->insertInternal($attributes); if ($transaction !== null) { @@ -822,7 +856,7 @@ class ActiveRecord extends Model return false; } $db = static::getDb(); - $transaction = $this->isOperationAtomic(self::OP_UPDATE) && $db->getTransaction() === null ? $db->beginTransaction() : null; + $transaction = $this->isTransactional(self::OP_UPDATE) && $db->getTransaction() === null ? $db->beginTransaction() : null; try { $result = $this->updateInternal($attributes); if ($transaction !== null) { @@ -929,7 +963,7 @@ class ActiveRecord extends Model public function delete() { $db = static::getDb(); - $transaction = $this->isOperationAtomic(self::OP_DELETE) && $db->getTransaction() === null ? $db->beginTransaction() : null; + $transaction = $this->isTransactional(self::OP_DELETE) && $db->getTransaction() === null ? $db->beginTransaction() : null; try { $result = false; if ($this->beforeDelete()) { @@ -1454,17 +1488,14 @@ class ActiveRecord extends Model } /** - * @param string $operation possible values are ActiveRecord::INSERT, ActiveRecord::UPDATE and ActiveRecord::DELETE. - * @return boolean whether given operation is atomic. Currently active scenario is taken into account. + * Returns a value indicating whether the specified operation is transactional in the current [[scenario]]. + * @param integer $operation the operation to check. Possible values are [[OP_INSERT]], [[OP_UPDATE]] and [[OP_DELETE]]. + * @return boolean whether the specified operation is transactional in the current [[scenario]]. */ - private function isOperationAtomic($operation) + public function isTransactional($operation) { $scenario = $this->getScenario(); - $scenarios = $this->scenarios(); - if (isset($scenarios[$scenario], $scenarios[$scenario]['atomic']) && is_array($scenarios[$scenario]['atomic'])) { - return in_array($operation, $scenarios[$scenario]['atomic']); - } else { - return false; - } + $transactions = $this->transactions(); + return isset($transactions[$scenario]) && ($transactions[$scenario] & $operation); } } From 22b5f9ea2c48f7c93e8e052922af13c66c56dab8 Mon Sep 17 00:00:00 2001 From: Qiang Xue Date: Thu, 8 Aug 2013 07:55:20 -0400 Subject: [PATCH 07/59] updated doc. --- docs/guide/active-record.md | 205 +++++++++++++++++++++++++++----------------- 1 file changed, 125 insertions(+), 80 deletions(-) diff --git a/docs/guide/active-record.md b/docs/guide/active-record.md index 20019be..bb39115 100644 --- a/docs/guide/active-record.md +++ b/docs/guide/active-record.md @@ -2,18 +2,21 @@ Active Record ============= ActiveRecord implements the [Active Record design pattern](http://en.wikipedia.org/wiki/Active_record). -The idea is that an ActiveRecord object is associated with a row in a database table so object properties are mapped -to columns of the corresponding database row. For example, a `Customer` object is associated with a row in the -`tbl_customer` table. +The idea is that an [[ActiveRecord]] object is associated with a row in a database table and its attributes are mapped +to the columns of the corresponding table columns. Reading an ActiveRecord attribute is equivalent to accessing +the corresponding table column. For example, a `Customer` object is associated with a row in the +`tbl_customer` table, and its `name` attribute is mapped to the `name` column in the `tbl_customer` table. +To get the value of the `name` column in the table row, you can simply use the expression `$customer->name`, +just like reading an object property. -Instead of writing raw SQL statements to access the data in the table, you can call intuitive methods available in the -corresponding ActiveRecord class to achieve the same goals. For example, calling [[save()]] would insert or update a row -in the underlying table: +Instead of writing raw SQL statements to perform database queries, you can call intuitive methods provided +by ActiveRecord to achieve the same goals. For example, calling [[ActiveRecord::save()|save()]] would +insert or update a row in the associated table of the ActiveRecord class: ```php $customer = new Customer(); $customer->name = 'Qiang'; -$customer->save(); +$customer->save(); // a new row is inserted into tbl_customer ``` @@ -24,7 +27,9 @@ To declare an ActiveRecord class you need to extend [[\yii\db\ActiveRecord]] and implement the `tableName` method like the following: ```php -class Customer extends \yii\db\ActiveRecord +use yii\db\ActiveRecord; + +class Customer extends ActiveRecord { /** * @return string the name of the table associated with this ActiveRecord class. @@ -52,8 +57,6 @@ return array( 'dsn' => 'mysql:host=localhost;dbname=testdb', 'username' => 'demo', 'password' => 'demo', - // turn on schema caching to improve performance in production mode - // 'schemaCacheDuration' => 3600, ), ), ); @@ -62,19 +65,22 @@ return array( Please read the [Database basics](database-basics.md) section to learn more on how to configure and use database connections. +> Tip: To use a different database connection, you may override the [[ActiveRecord::getDb()]] method. +You may create a base ActiveRecord class and override its [[ActiveRecord::getDb()]] method. You +then extend from this base class for all those ActiveRecord classes that need to use the same +DB connection. -Getting Data from Database --------------------------- -There are two ActiveRecord methods for getting data from database: +Querying Data from Database +--------------------------- -- [[find()]] -- [[findBySql()]] +There are two ActiveRecord methods for querying data from database: -They both return an [[ActiveQuery]] instance. Coupled with various query methods provided -by [[ActiveQuery]], ActiveRecord supports very flexible and powerful data retrieval approaches. + - [[ActiveRecord::find()]] + - [[ActiveRecord::findBySql()]] -The followings are some examples, +They both return an [[ActiveQuery]] instance which extends from [[Query]] and thus supports +the same set of flexible and powerful DB query methods. The followings are some examples, ```php // to retrieve all *active* customers and order them by their ID: @@ -101,8 +107,10 @@ $count = Customer::find() ->count(); // to return customers in terms of arrays rather than `Customer` objects: -$customers = Customer::find()->asArray()->all(); -// each $customers element is an array of name-value pairs +$customers = Customer::find() + ->asArray() + ->all(); +// each element of $customers is an array of name-value pairs // to index the result by customer IDs: $customers = Customer::find()->indexBy('id')->all(); @@ -115,9 +123,9 @@ Accessing Column Data ActiveRecord maps each column of the corresponding database table row to an *attribute* in the ActiveRecord object. An attribute is like a regular object property whose name is the same as the corresponding column -name and is case sensitive. +name and is case-sensitive. -To read the value of a column, we can use the following expression: +To read the value of a column, you can use the following expression: ```php // "id" is the name of a column in the table associated with $customer ActiveRecord object @@ -126,28 +134,29 @@ $id = $customer->id; $id = $customer->getAttribute('id'); ``` -We can get all column values through the [[attributes]] property: +You can get all column values through the [[ActiveRecord::attributes]] property: ```php $values = $customer->attributes; ``` -Saving Data to Database ------------------------ +Manipulating Data in Database +----------------------------- ActiveRecord provides the following methods to insert, update and delete data in the database: -- [[save()]] -- [[insert()]] -- [[update()]] -- [[delete()]] -- [[updateCounters()]] -- [[updateAll()]] -- [[updateAllCounters()]] -- [[deleteAll()]] - -Note that [[updateAll()]], [[updateAllCounters()]] and [[deleteAll()]] apply to the whole database +- [[ActiveRecord::save()|save()]] +- [[ActiveRecord::insert()|insert()]] +- [[ActiveRecord::update()|update()]] +- [[ActiveRecord::delete()|delete()]] +- [[ActiveRecord::updateCounters()|updateCounters()]] +- [[ActiveRecord::updateAll()|updateAll()]] +- [[ActiveRecord::updateAllCounters()|updateAllCounters()]] +- [[ActiveRecord::deleteAll()|deleteAll()]] + +Note that [[ActiveRecord::updateAll()|updateAll()]], [[ActiveRecord::updateAllCounters()|updateAllCounters()]] +and [[ActiveRecord::deleteAll()|deleteAll()]] are static methods and apply to the whole database table, while the rest of the methods only apply to the row associated with the ActiveRecord object. The followings are some examples: @@ -163,25 +172,25 @@ $customer->save(); // equivalent to $customer->insert(); $customer = Customer::find($id); $customer->email = 'james@example.com'; $customer->save(); // equivalent to $customer->update(); -// Note that model attributes will be validated first and -// model will not be saved unless it's valid. // to delete an existing customer record $customer = Customer::find($id); $customer->delete(); -// to increment the age of all customers by 1 +// to increment the age of ALL customers by 1 Customer::updateAllCounters(array('age' => 1)); ``` -Getting Relational Data ------------------------ +Querying Relational Data +------------------------ -Using ActiveRecord you can expose relationships as properties. For example, with an appropriate declaration, -`$customer->orders` can return an array of `Order` objects which represent the orders placed by the specified customer. +You can use ActiveRecord to query the relational data of a table. The relational data returned can +be accessed like a property of the ActiveRecord object associated with the primary table. +For example, with an appropriate relation declaration, by accessing `$customer->orders` you may obtain +an array of `Order` objects which represent the orders placed by the specified customer. -To declare a relationship, define a getter method which returns an [[ActiveRelation]] object. For example, +To declare a relation, define a getter method which returns an [[ActiveRelation]] object. For example, ```php class Customer extends \yii\db\ActiveRecord @@ -201,35 +210,42 @@ class Order extends \yii\db\ActiveRecord } ``` -Within the getter methods above, we call [[hasMany()]] or [[hasOne()]] methods to -create a new [[ActiveRelation]] object. The [[hasMany()]] method declares -a one-many relationship. For example, a customer has many orders. And the [[hasOne()]] -method declares a many-one or one-one relationship. For example, an order has one customer. -Both methods take two parameters: +The methods [[ActiveRecord::hasMany()]] and [[ActiveRecord::hasOne()]] used in the above +are used to model the many-one relationship and one-one relationship in a relational database. +For example, a customer has many orders, and an order has one customer. +Both methods take two parameters and return an [[ActiveRelation]] object: -- `$class`: the name of the class of the related model(s). If specified without - a namespace, the namespace of the related model class will be taken from the declaring class. -- `$link`: the association between columns from the two tables. This should be given as an array. - The keys of the array are the names of the columns from the table associated with `$class`, - while the values of the array are the names of the columns from the declaring class. - It is a good practice to define relationships based on table foreign keys. + - `$class`: the name of the class of the related model(s). If specified without + a namespace, the namespace of the related model class will be taken from the declaring class. + - `$link`: the association between columns from the two tables. This should be given as an array. + The keys of the array are the names of the columns from the table associated with `$class`, + while the values of the array are the names of the columns from the declaring class. + It is a good practice to define relationships based on table foreign keys. -After declaring relationships getting relational data is as easy as accessing -a component property that is defined by the getter method: +After declaring relations, getting relational data is as easy as accessing a component property +that is defined by the corresponding getter method: ```php -// the orders of a customer -$customer = Customer::find($id); +// get the orders of a customer +$customer = Customer::find(1); $orders = $customer->orders; // $orders is an array of Order objects +``` + +Behind the scene, the above code executes the following two SQL queries, one for each line of code: -// the customer of the first order -$customer2 = $orders[0]->customer; // $customer == $customer2 +```sql +SELECT * FROM tbl_customer WHERE id=1; +SELECT * FROM tbl_order WHERE customer_id=1; ``` -Because [[ActiveRelation]] extends from [[ActiveQuery]], it has the same query building methods, -which allows us to customize the query for retrieving the related objects. -For example, we may declare a `bigOrders` relationship which returns orders whose -subtotal exceeds certain amount: +> Tip: If you access the expression `$customer->orders` again, will it perform the second SQL query again? +Nope. The SQL query is only performed the first time when this expression is accessed. Any further +accesses will only return the previously fetched results that are cached internally. If you want to re-query +the relational data, simply unset the existing one first: `unset($customer->orders);`. + +Sometimes, you may want to pass parameters to a relational query. For example, instead of returning +all orders of a customer, you may want to return only big orders whose subtotal exceeds a specified amount. +To do so, declare a `bigOrders` relation with the following getter method: ```php class Customer extends \yii\db\ActiveRecord @@ -243,8 +259,22 @@ class Customer extends \yii\db\ActiveRecord } ``` +Remember that `hasMany()` returns an [[ActiveRelation]] object which extends from [[ActiveQuery]] +and thus supports the same set of querying methods as [[ActiveQuery]]. + +With the above declaration, if you access `$customer->bigOrders`, it will only return the orders +whose subtotal is greater than 100. To specify a different threshold value, use the following code: + +```php +$orders = $customer->getBigOrders(200)->all(); +``` + + +Relations with Pivot Table +-------------------------- + Sometimes, two tables are related together via an intermediary table called -[pivot table](http://en.wikipedia.org/wiki/Pivot_table). To declare such relationships, we can customize +[pivot table](http://en.wikipedia.org/wiki/Pivot_table). To declare such relations, we can customize the [[ActiveRelation]] object by calling its [[ActiveRelation::via()]] or [[ActiveRelation::viaTable()]] method. @@ -283,7 +313,10 @@ class Order extends \yii\db\ActiveRecord ``` -When you access the related objects the first time, behind the scene ActiveRecord performs a DB query +Lazy and Eager Loading +---------------------- + +As described earlier, when you access the related objects the first time, ActiveRecord will perform a DB query to retrieve the corresponding data and populate it into the related objects. No query will be performed if you access the same related objects again. We call this *lazy loading*. For example, @@ -296,9 +329,7 @@ $orders = $customer->orders; $orders2 = $customer->orders; ``` - -Lazy loading is very convenient to use. However, it may suffer from performance -issue in the following scenario: +Lazy loading is very convenient to use. However, it may suffer from a performance issue in the following scenario: ```php // SQL executed: SELECT * FROM tbl_customer LIMIT 100 @@ -313,12 +344,12 @@ foreach ($customers as $customer) { How many SQL queries will be performed in the above code, assuming there are more than 100 customers in the database? 101! The first SQL query brings back 100 customers. Then for each customer, a SQL query -is performed to bring back the customer's orders. +is performed to bring back the orders of that customer. To solve the above performance problem, you can use the so-called *eager loading* approach by calling [[ActiveQuery::with()]]: ```php -// SQL executed: SELECT * FROM tbl_customer LIMIT 100 +// SQL executed: SELECT * FROM tbl_customer LIMIT 100; // SELECT * FROM tbl_orders WHERE customer_id IN (1,2,...) $customers = Customer::find()->limit(100) ->with('orders')->all(); @@ -333,7 +364,7 @@ foreach ($customers as $customer) { As you can see, only two SQL queries are needed for the same task. -Sometimes, you may want to customize the relational queries on the fly. It can be +Sometimes, you may want to customize the relational queries on the fly. This can be done for both lazy loading and eager loading. For example, ```php @@ -357,8 +388,8 @@ Working with Relationships ActiveRecord provides the following two methods for establishing and breaking a relationship between two ActiveRecord objects: -- [[link()]] -- [[unlink()]] +- [[ActiveRecord::link()|link()]] +- [[ActiveRecord::unlink()|unlink()]] For example, given a customer and a new order, we can use the following code to make the order owned by the customer: @@ -378,9 +409,9 @@ Data Input and Validation ------------------------- ActiveRecord inherits data validation and data input features from [[\yii\base\Model]]. Data validation is called -automatically when `save()` is performed and is canceling saving in case attributes aren't valid. +automatically when `save()` is performed. If data validation fails, the saving operation will be cancelled. -For more details refer to [Model](model.md) section of the guide. +For more details refer to the [Model](model.md) section of this guide. Life Cycles of an ActiveRecord Object @@ -419,7 +450,7 @@ Finally when calling [[delete()]] to delete an ActiveRecord, we will have the fo Scopes ------ -A scope is a method that customizes a given [[ActiveQuery]] object. Scope methods are defined +A scope is a method that customizes a given [[ActiveQuery]] object. Scope methods are static and are defined in the ActiveRecord classes. They can be invoked through the [[ActiveQuery]] object that is created via [[find()]] or [[findBySql()]]. The following is an example: @@ -466,12 +497,16 @@ $customers = Customer::find()->olderThan(50)->all(); The parameters should follow after the `$query` parameter when defining the scope method, and they can take default values like shown above. -Atomic operations and scenarios -------------------------------- + +Transactional operations +------------------------ + + +When a few DB operations are related and are executed TODO: FIXME: WIP, TBD, https://github.com/yiisoft/yii2/issues/226 -Imagine situation where you have to save something related to the main model in [[beforeSave()]], +, [[afterSave()]], [[beforeDelete()]] and/or [[afterDelete()]] life cycle methods. Developer may come to the solution of overriding ActiveRecord [[save()]] method with database transaction wrapping or even using transaction in controller action, which is strictly speaking doesn't seems to be a good @@ -596,6 +631,16 @@ class ProductController extends \yii\web\Controller } ``` +Optimistic Locks +---------------- + +TODO + +Dirty Attributes +---------------- + +TODO + See also -------- From 2409624894cde7ac3934e0ddf8f87aa7d14c48c9 Mon Sep 17 00:00:00 2001 From: Ryadnov <2008.big@gmail.com> Date: Thu, 8 Aug 2013 21:15:46 +0400 Subject: [PATCH 08/59] fix typos - `Yii::app()` --- framework/yii/web/Response.php | 2 +- framework/yii/widgets/Menu.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/framework/yii/web/Response.php b/framework/yii/web/Response.php index 6bb888c..c7855f6 100644 --- a/framework/yii/web/Response.php +++ b/framework/yii/web/Response.php @@ -515,7 +515,7 @@ class Response extends \yii\base\Response * **Example** * * ~~~ - * Yii::app()->request->xSendFile('/home/user/Pictures/picture1.jpg'); + * Yii::$app->request->xSendFile('/home/user/Pictures/picture1.jpg'); * ~~~ * * @param string $filePath file name with full path diff --git a/framework/yii/widgets/Menu.php b/framework/yii/widgets/Menu.php index 5b5d48c..40fd479 100644 --- a/framework/yii/widgets/Menu.php +++ b/framework/yii/widgets/Menu.php @@ -37,7 +37,7 @@ use yii\helpers\Html; * array('label' => 'New Arrivals', 'url' => array('product/index', 'tag' => 'new')), * array('label' => 'Most Popular', 'url' => array('product/index', 'tag' => 'popular')), * )), - * array('label' => 'Login', 'url' => array('site/login'), 'visible' => Yii::app()->user->isGuest), + * array('label' => 'Login', 'url' => array('site/login'), 'visible' => Yii::$app->user->isGuest), * ), * )); * ~~~ From 0367d0a6a4994b2c42581b9c5699c70ab5e9833b Mon Sep 17 00:00:00 2001 From: Ryadnov <2008.big@gmail.com> Date: Thu, 8 Aug 2013 21:24:00 +0400 Subject: [PATCH 09/59] fixes initializing attributes in Sort class --- framework/yii/data/Sort.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/framework/yii/data/Sort.php b/framework/yii/data/Sort.php index 4d7851a..bddc96b 100644 --- a/framework/yii/data/Sort.php +++ b/framework/yii/data/Sort.php @@ -203,6 +203,8 @@ class Sort extends Object 'desc' => array($name => self::DESC), 'label' => Inflector::camel2words($name), ), $attribute); + } else { + $attributes[$name] = $attribute; } } $this->attributes = $attributes; From e3801fbf6bdf167c31f4f2bbb774f75659956d57 Mon Sep 17 00:00:00 2001 From: Qiang Xue Date: Thu, 8 Aug 2013 20:00:48 -0400 Subject: [PATCH 10/59] Upgraded bootstrap to 3.0RC1. --- apps/advanced/backend/config/AppAsset.php | 2 +- apps/advanced/frontend/config/AppAsset.php | 2 +- apps/basic/config/AppAsset.php | 2 +- apps/basic/views/layouts/main.php | 33 +- apps/basic/views/site/contact.php | 30 +- apps/basic/views/site/index.php | 53 +- apps/basic/views/site/login.php | 18 +- apps/basic/web/css/site.css | 124 +- framework/yii/bootstrap/AffixAsset.php | 26 - framework/yii/bootstrap/AlertAsset.php | 26 - framework/yii/bootstrap/BootstrapAsset.php | 2 + framework/yii/bootstrap/BootstrapPluginAsset.php | 27 + framework/yii/bootstrap/ButtonAsset.php | 26 - framework/yii/bootstrap/CarouselAsset.php | 26 - framework/yii/bootstrap/CollapseAsset.php | 26 - framework/yii/bootstrap/DropdownAsset.php | 26 - framework/yii/bootstrap/ModalAsset.php | 26 - framework/yii/bootstrap/NavBar.php | 21 +- framework/yii/bootstrap/PopoverAsset.php | 24 - framework/yii/bootstrap/Progress.php | 6 +- framework/yii/bootstrap/ResponsiveAsset.php | 24 - framework/yii/bootstrap/ScrollspyAsset.php | 26 - framework/yii/bootstrap/TabAsset.php | 26 - framework/yii/bootstrap/TooltipAsset.php | 26 - framework/yii/bootstrap/TransitionAsset.php | 25 - framework/yii/bootstrap/TypeaheadAsset.php | 26 - framework/yii/bootstrap/Widget.php | 17 +- framework/yii/bootstrap/assets.php | 24 - .../bootstrap/assets/css/bootstrap-glyphicons.css | 2 + .../bootstrap/assets/css/bootstrap-responsive.css | 1109 --- .../assets/css/bootstrap-responsive.min.css | 9 - framework/yii/bootstrap/assets/css/bootstrap.css | 7236 ++++++++------------ .../yii/bootstrap/assets/css/bootstrap.min.css | 8 +- .../assets/fonts/glyphiconshalflings-regular.eot | Bin 0 -> 33358 bytes .../assets/fonts/glyphiconshalflings-regular.otf | Bin 0 -> 18116 bytes .../assets/fonts/glyphiconshalflings-regular.svg | 175 + .../assets/fonts/glyphiconshalflings-regular.ttf | Bin 0 -> 32896 bytes .../assets/fonts/glyphiconshalflings-regular.woff | Bin 0 -> 18944 bytes .../assets/img/glyphicons-halflings-white.png | Bin 8777 -> 0 bytes .../bootstrap/assets/img/glyphicons-halflings.png | Bin 12799 -> 0 bytes .../yii/bootstrap/assets/js/bootstrap-affix.js | 117 - .../yii/bootstrap/assets/js/bootstrap-alert.js | 99 - .../yii/bootstrap/assets/js/bootstrap-button.js | 105 - .../yii/bootstrap/assets/js/bootstrap-carousel.js | 207 - .../yii/bootstrap/assets/js/bootstrap-collapse.js | 167 - .../yii/bootstrap/assets/js/bootstrap-dropdown.js | 169 - .../yii/bootstrap/assets/js/bootstrap-modal.js | 247 - .../yii/bootstrap/assets/js/bootstrap-popover.js | 114 - .../yii/bootstrap/assets/js/bootstrap-scrollspy.js | 162 - framework/yii/bootstrap/assets/js/bootstrap-tab.js | 144 - .../yii/bootstrap/assets/js/bootstrap-tooltip.js | 361 - .../bootstrap/assets/js/bootstrap-transition.js | 60 - .../yii/bootstrap/assets/js/bootstrap-typeahead.js | 335 - framework/yii/bootstrap/assets/js/bootstrap.js | 1948 ++++++ framework/yii/bootstrap/assets/js/bootstrap.min.js | 6 + framework/yii/debug/DebugAsset.php | 2 +- framework/yii/debug/assets/main.css | 106 +- framework/yii/debug/panels/RequestPanel.php | 2 +- framework/yii/debug/views/default/index.php | 16 +- framework/yii/debug/views/default/toolbar.css | 2 +- framework/yii/debug/views/default/view.php | 32 +- framework/yii/helpers/HtmlBase.php | 34 +- framework/yii/widgets/ActiveField.php | 43 +- framework/yii/widgets/ActiveForm.php | 4 +- framework/yii/widgets/Breadcrumbs.php | 2 +- framework/yii/widgets/LinkPager.php | 15 +- framework/yii/widgets/LinkSorter.php | 15 +- 67 files changed, 5355 insertions(+), 8418 deletions(-) delete mode 100644 framework/yii/bootstrap/AffixAsset.php delete mode 100644 framework/yii/bootstrap/AlertAsset.php create mode 100644 framework/yii/bootstrap/BootstrapPluginAsset.php delete mode 100644 framework/yii/bootstrap/ButtonAsset.php delete mode 100644 framework/yii/bootstrap/CarouselAsset.php delete mode 100644 framework/yii/bootstrap/CollapseAsset.php delete mode 100644 framework/yii/bootstrap/DropdownAsset.php delete mode 100644 framework/yii/bootstrap/ModalAsset.php delete mode 100644 framework/yii/bootstrap/PopoverAsset.php delete mode 100644 framework/yii/bootstrap/ResponsiveAsset.php delete mode 100644 framework/yii/bootstrap/ScrollspyAsset.php delete mode 100644 framework/yii/bootstrap/TabAsset.php delete mode 100644 framework/yii/bootstrap/TooltipAsset.php delete mode 100644 framework/yii/bootstrap/TransitionAsset.php delete mode 100644 framework/yii/bootstrap/TypeaheadAsset.php delete mode 100644 framework/yii/bootstrap/assets.php create mode 100644 framework/yii/bootstrap/assets/css/bootstrap-glyphicons.css delete mode 100644 framework/yii/bootstrap/assets/css/bootstrap-responsive.css delete mode 100644 framework/yii/bootstrap/assets/css/bootstrap-responsive.min.css create mode 100644 framework/yii/bootstrap/assets/fonts/glyphiconshalflings-regular.eot create mode 100644 framework/yii/bootstrap/assets/fonts/glyphiconshalflings-regular.otf create mode 100644 framework/yii/bootstrap/assets/fonts/glyphiconshalflings-regular.svg create mode 100644 framework/yii/bootstrap/assets/fonts/glyphiconshalflings-regular.ttf create mode 100644 framework/yii/bootstrap/assets/fonts/glyphiconshalflings-regular.woff delete mode 100644 framework/yii/bootstrap/assets/img/glyphicons-halflings-white.png delete mode 100644 framework/yii/bootstrap/assets/img/glyphicons-halflings.png delete mode 100644 framework/yii/bootstrap/assets/js/bootstrap-affix.js delete mode 100644 framework/yii/bootstrap/assets/js/bootstrap-alert.js delete mode 100644 framework/yii/bootstrap/assets/js/bootstrap-button.js delete mode 100644 framework/yii/bootstrap/assets/js/bootstrap-carousel.js delete mode 100644 framework/yii/bootstrap/assets/js/bootstrap-collapse.js delete mode 100644 framework/yii/bootstrap/assets/js/bootstrap-dropdown.js delete mode 100644 framework/yii/bootstrap/assets/js/bootstrap-modal.js delete mode 100644 framework/yii/bootstrap/assets/js/bootstrap-popover.js delete mode 100644 framework/yii/bootstrap/assets/js/bootstrap-scrollspy.js delete mode 100644 framework/yii/bootstrap/assets/js/bootstrap-tab.js delete mode 100644 framework/yii/bootstrap/assets/js/bootstrap-tooltip.js delete mode 100644 framework/yii/bootstrap/assets/js/bootstrap-transition.js delete mode 100644 framework/yii/bootstrap/assets/js/bootstrap-typeahead.js create mode 100644 framework/yii/bootstrap/assets/js/bootstrap.js create mode 100644 framework/yii/bootstrap/assets/js/bootstrap.min.js diff --git a/apps/advanced/backend/config/AppAsset.php b/apps/advanced/backend/config/AppAsset.php index 944807a..90a850d 100644 --- a/apps/advanced/backend/config/AppAsset.php +++ b/apps/advanced/backend/config/AppAsset.php @@ -23,6 +23,6 @@ class AppAsset extends AssetBundle ); public $depends = array( 'yii\web\YiiAsset', - 'yii\bootstrap\ResponsiveAsset', + 'yii\bootstrap\BootstrapAsset', ); } diff --git a/apps/advanced/frontend/config/AppAsset.php b/apps/advanced/frontend/config/AppAsset.php index 0ba2c1d..1801661 100644 --- a/apps/advanced/frontend/config/AppAsset.php +++ b/apps/advanced/frontend/config/AppAsset.php @@ -23,6 +23,6 @@ class AppAsset extends AssetBundle ); public $depends = array( 'yii\web\YiiAsset', - 'yii\bootstrap\ResponsiveAsset', + 'yii\bootstrap\BootstrapAsset', ); } diff --git a/apps/basic/config/AppAsset.php b/apps/basic/config/AppAsset.php index 94369bf..3e22b9b 100644 --- a/apps/basic/config/AppAsset.php +++ b/apps/basic/config/AppAsset.php @@ -24,6 +24,6 @@ class AppAsset extends AssetBundle ); public $depends = array( 'yii\web\YiiAsset', - 'yii\bootstrap\ResponsiveAsset', + 'yii\bootstrap\BootstrapAsset', ); } diff --git a/apps/basic/views/layouts/main.php b/apps/basic/views/layouts/main.php index 5f8603f..2b32d5b 100644 --- a/apps/basic/views/layouts/main.php +++ b/apps/basic/views/layouts/main.php @@ -21,26 +21,19 @@ app\config\AppAsset::register($this); beginBody(); ?>
-

My Company

+

My Company

- - + array('class' => 'nav navbar-nav nav-justified'), + 'items' => array( + array('label' => 'Home', 'url' => array('/site/index')), + array('label' => 'About', 'url' => array('/site/about')), + array('label' => 'Contact', 'url' => array('/site/contact')), + Yii::$app->user->isGuest ? + array('label' => 'Login', 'url' => array('/site/login')) : + array('label' => 'Logout (' . Yii::$app->user->identity->username .')' , 'url' => array('/site/logout')), + ), + )); ?>
-
-