Commit 35eea62c by Riverlet

Merge branch 'master' of https://github.com/yiisoft/yii2

parents c15a5a1f 604b464e
...@@ -17,6 +17,7 @@ AppAsset::register($this); ...@@ -17,6 +17,7 @@ AppAsset::register($this);
<head> <head>
<meta charset="<?= Yii::$app->charset ?>"/> <meta charset="<?= Yii::$app->charset ?>"/>
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<?= Html::csrfMetaTags() ?>
<title><?= Html::encode($this->title) ?></title> <title><?= Html::encode($this->title) ?></title>
<?php $this->head() ?> <?php $this->head() ?>
</head> </head>
......
...@@ -18,6 +18,7 @@ AppAsset::register($this); ...@@ -18,6 +18,7 @@ AppAsset::register($this);
<head> <head>
<meta charset="<?= Yii::$app->charset ?>"/> <meta charset="<?= Yii::$app->charset ?>"/>
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<?= Html::csrfMetaTags() ?>
<title><?= Html::encode($this->title) ?></title> <title><?= Html::encode($this->title) ?></title>
<?php $this->head() ?> <?php $this->head() ?>
</head> </head>
......
...@@ -17,6 +17,7 @@ AppAsset::register($this); ...@@ -17,6 +17,7 @@ AppAsset::register($this);
<head> <head>
<meta charset="<?= Yii::$app->charset ?>"/> <meta charset="<?= Yii::$app->charset ?>"/>
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<?= Html::csrfMetaTags() ?>
<title><?= Html::encode($this->title) ?></title> <title><?= Html::encode($this->title) ?></title>
<?php $this->head() ?> <?php $this->head() ?>
</head> </head>
......
Generando Código con Gii
========================
En esta sección, explicaremos cómo utilizar [Gii](tool-gii.md) para generar código que automáticamente
implementa algunas características comunes de una aplicación. Para lograrlo, todo lo que tienes que hacer es
ingresar la información de acuerdo a las instrucciones mostradas en la páginas web de Gii.
A lo largo de este tutorial, aprenderás
* Cómo activar Gii en tu aplicación;
* Cómo utilizar Gii para generar una clase Active Record;
* Cómo utilizar Gii para generar el código que implementa las operaciones ABM de una tabla de la base de datos.
* Cómo personalizar el código generado por Gii.
Comenzando con Gii <a name="starting-gii"></a>
------------------
[Gii](tool-gii.md) es provisto por Yii en forma de [módulo](structure-modules.md). Puedes habilitar Gii
configurándolo en la propiedad [[yii\base\Application::modules|modules]] de la aplicación. En particular,
puedes encontrar que el siguiente código ya está incluido en el archivo `config/web.php` - la configuración de la aplicación,
```php
$config = [ ... ];
if (YII_ENV_DEV) {
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = 'yii\gii\Module';
}
```
La configuración mencionada arriba dice que al estar en el [entorno de desarrollo](concept-configurations.md#environment-constants),
la aplicación debe incluir un módulo llamado `gii`, cuya clase es [[yii\gii\Module]].
Si chequeas el [script de entrada](structure-entry-scripts.md) `web/index.php` de tu aplicación, encontrarás la línea
que esencialmente define la constante `YII_ENV_DEV` como true.
```php
defined('YII_ENV') or define('YII_ENV', 'dev');
```
De esta manera, tu aplicación ha habilitado Gii, y puedes acceder al módulo a través de la URL:
```
http://hostname/index.php?r=gii
```
![Gii](images/start-gii.png)
Generando una Clase Active Record <a name="generating-ar"></a>
---------------------------------
Para poder generar una clase Active Record con Gii, selecciona "Model Generator" completa el formulario de la siguiente manera,
* Table Name: `country`
* Model Class: `Country`
![Model Generator](images/start-gii-model.png)
Haz click el el botón "Preview". Verás que `models/Country.php` es listado en el cuadro de resultado.
Puedes hacer click en él para previsualizar su contenido.
Debido a que en la última sección ya habías creado el archivo `models/Country.php`, si haces click
en el botón `diff` cercano al nombre del archivo, verás las diferencias entre el código a ser generado
y el código que ya habías escrito.
![Previsualización del Model Generator](images/start-gii-model-preview.png)
Marca el checkbox que se encuentra al lado de "overwrite" y entonces haz click en el botón "Generate".
Verás una página de confirmación indicando que el código ha sido generado correctamente y tu archivo `models/Country.php`
ha sido sobrescrito con el código generado ahora.
Generando código de ABM (CRUD en inglés) <a name="generating-crud"></a>
----------------------------------------
Para generar un ABM, selecciona "CRUD Generator". Completa el formulario de esta manera:
* Model Class: `app\models\Country`
* Search Model Class: `app\models\CountrySearch`
* Controller Class: `app\controllers\CountryController`
![Generador de ABM](images/start-gii-crud.png)
Al hacer click en el botón "Preview" verás la lista de archivos a ser generados.
Asegúrate de haber marcado el checkbox de sobrescribir (overwrite) para ambos archivos: `controllers/CountryController.php` y
`views/country/index.php`. Esto es necesario ya que los archivos habían sido creados manualmente antes
en la sección anterior y ahora los quieres sobrescribir para poder tener un ABM funcional.
Intentándolo <a name="trying-it-out"></a>
------------
Para ver cómo funciona, accede desde tu navegador a la siguiente URL:
```
http://hostname/index.php?r=country/index
```
Verás una grilla de datos mostrando los países de la base de datos. Puedes ordenar la grilla
o filtrar los resultados escribiendo alguna condición en los encabezados de las columnas.
Por cada país mostrado en la grilla, puedes elegir ver el registro en completo, actualizarlo o eliminarlo.
Puedes incluso hacer click en el botón "Create Country" que se encuentra sobre la grilla y así cargar
un nuevo país en la base de datos.
![Grilla de Países](images/start-gii-country-grid.png)
![Actualizando un País](images/start-gii-country-update.png)
La siguiente es la lista de archivos generados en caso de que quieras inspeccionar cómo el ABM está generado,
o si quisieras personalizarlos.
* Controlador: `controllers/CountryController.php`
* Modelos: `models/Country.php` y `models/CountrySearch.php`
* Vistas: `views/country/*.php`
> Información: Gii está diseñado para ser una herramienta altamente configurable. Utilizándola con sabiduría
puede acelerar enormemente la velocidad de desarrollo de tu aplicación. Para más detalles, consulta la
sección [Gii](tool-gii.md).
Resumen <a name="summary"></a>
-------
En esta sección, has aprendido a utilizar Gii para generar el código que implementa completamente las características
de un ABM de acuerdo a una determinada tabla de la base de datos.
Diciendo Hola
============
Esta sección describe cómo crear una nueva página "Hola" en tu aplicación.
Para lograr este objetivo, vas a crear un [action](structure-controllers.md#creating-actions) (una acción) y
un [view](structure-views.md) (una vista):
* La aplicación enviará la petición de la página a la acción
* y la acción regresará el render de la vista que muestra la palabra "Hola" al usuario final.
A lo largo de este tutorial, aprenderás tres cosas:
1. Cómo crear un [action](structure-controllers.md) (acción) para responder peticiones (request),
2. cómo crear un [view](structure-views.md) (vista) para armar el contenido de la respuesta, y
3. cómo una aplicación responde una petición a [actions](structure-controllers.md#creating-actions).
Creando una Acción <a name="creating-action"></a>
------------------
Para la tarea "Hola", crearás un [action](structure-controllers.md#creating-actions) `dice` que lee
un parámetro `mensaje` de la petición y muestra este mensaje de vuelta al usuario. Si la petición
no provee un parámetro `mensaje`, la acción mostrará el mensaje por defecto "Hola".
> Info: [Actions](structure-controllers.md#creating-actions) son objetos que los usuarios finales pueden utilizar directamente para
su ejecución. Las Acciones están agrupadas por [controllers](structure-controllers.md) (controladores). El resultado de la ejecución de
una acción es la respuesta que el usuario final recibirá.
Las Acciones deben ser declaradas en [controllers](structure-controllers.md). Para simplificar, puedes
declarar la acción `dice` en el `SiteController` existente. Este controlador está definido
en el archivo de clase `controllers/SiteController.php`. Aquí está el inicio de la nueva acción:
```php
<?php
namespace app\controllers;
use yii\web\Controller;
class SiteController extends Controller
{
// ...código existente...
public function actionDice($mensaje = 'Hola')
{
return $this->render('dice', ['mensaje' => $mensaje]);
}
}
```
En el código de arriba, la acción `dice` está definida por un método llamado `actionDice` en la clase `SiteController`.
Yii utiliza el prefijo `action` para diferenciar los métodos de acciones de otros métodos en las clases de los controladores.
El nombre que le sigue al prefijo `action` se mapea al ID de la acción.
Cuando se trata de nombrar las acciones, debes entender como Yii trata los ID de las acciones. Los ID de las acciones siempre son
referenciados en minúscula. Si un ID de acción requiere múltiples palabras, estas serán concatenadas con guiones
(p.e., `crear-comentario`). Los nombres de los métodos de las acciones son mapeados a los ID de las acciones
removiendo los guiones, colocando en mayúscula la primera letra de cada palabra, y colocando el prefijo `action` al resultado. Por ejemplo,
el ID de la acción `crear-comentario` corresponde al nombre de método de acción `actionCrearComentario`.
El método de acción en nuestro ejemplo toma un parámetro `$mensaje`, el cual tiene como valor por defecto `"Hola"` (de la misma manera
que se coloca un valor por defecto a un argumento en cualquier función o método en PHP). Cuando una aplicación
recibe una petición y determina que la acción `dice` es responsable de manejar dicha petición, la aplicación llenará
el parámetro con el parámetro que tenga el mismo nombre en la petición. En otras palabras, si la petición incluye un
parámetro `mensaje` con el valor de `"Adios"`, la variable `$mensaje` dentro de la acción será sustituida por este valor.
Dentro del método de acción, [[yii\web\Controller::render()|render()]] es llamado para hacer render (mostrar o visualizar) un
archivo [view](structure-views.md) llamado `dice`. El parámetro `mensaje` tambien es pasado al view para que pueda ser utilizado ahí.
El resultado es regresado al método action. Ese resultado será recibido por la aplicación y mostrado al usuario final en el
navegador (como parte de una página HTML completa).
Creando una Vista <a name="creating-view"></a>
-----------------
[Views](structure-views.md) (vistas) son scripts que escribes para generar una respuesta de contenido.
Para la tarea "Hola", vas a crear una vista `dice` que imprime el parámetro `mensaje` recibido desde el método action, y pasado por la acción a la vista:
```php
<?php
use yii\helpers\Html;
?>
<?= Html::encode($mensaje) ?>
```
El view `dice` debe ser guardado en el archivo `views/site/dice.php`. Cuando el método [[yii\web\Controller::render()|render()]]
es llamado en una acción, buscará un archivo PHP llamado `views/ControllerID/NombreView.php`.
Nota que en el código de arriba, el parámetro `mensaje` es [[yii\helpers\Html::encode()|HTML-encoded]]
antes de ser impreso. Esto es necesario ya que el parámetro viene de un usuario final, haciéndolo vulnerable a
[ataques cross-site scripting (XSS)](http://es.wikipedia.org/wiki/Cross-site_scripting) pudiendo inyectar código de Javascript malicioso dentro del parámetro.
Naturalmente, puedes colocar mas contenido en el view `dice`. El contenido puede consistir de etiquetas HTML, texto plano, e inlcusive código PHP.
De hecho, el view `dice` es sólo un script PHP que es ejecutado por el método [[yii\web\Controller::render()|render()]].
El contenido impreso por el script view será regresado a la aplicación como la respuesta del resultado. La aplicación a cambio mostrará el resultado al usuario final.
Probando <a name="trying-it-out"></a>
--------
Después de crear la acción y la vista, puedes abrir la nueva página abriendo el siguiente URL:
```
http://hostname/index.php?r=site/dice&mensaje=Hello+World
```
![Hello World](images/start-hello-world.png)
Esta URL resultará en una página mostrando "Hello World". La página comparte el mismo encabezado y pie de página de las otras páginas de la aplicación.
Si omites el parámetro `mensaje` en el URL, verás que la página muestra sólo "Hola". Esto es porque `mensaje` es pasado como un parámetro al método `actionDice()`, y cuando es omitido, el valor por defecto `"Hola"` será utilizado.
> Info: La nueva página comparte el mismo encabezado y pie de página que otras páginas porque el método [[yii\web\Controller::render()|render()]]
automáticamente inyectará el resultado del view `dice` en la plantilla [layout](structure-views.md#layouts) que en este
caso está localizada en `views/layouts/main.php`.
El parámetro `r` en el URL de arriba requiere más explicación. Significa [route](runtime-routing.md) (ruta), y es el ID amplio y único de una aplicación
que refiere a una acción. El formato de las rutas es `ControllerID/ActionID`. Cuando la aplicación recibe una petición, revisará este parámetro, utilizando la parte del `ControllerID` para determinar cual clase de controlador será inicializado para manejar la petición. Entonces, el controlador utilizará la parte `ActionID` para determinar cual acción debe ser inizializada para hacer realmente el trabajo. En este ejemplo, la ruta `site/dice`
será respondida por la clase controlador `SiteController` y la acción `dice`. Como resultado,
el método `SiteController::actionDice()` será llamado para manejar el requerimiento.
> Info: Al igual que las acciones, los controladores tambien tienen ID únicos que los identifican en una aplicación.
Los ID de los Controladores utilizan las mismas reglas de nombrado que los ID de las acciones. Los nombres de las clases de los Controladores son derivados de los ID de los controladores removiendo los guiones de los ID, colocando la primera letra en mayúscula en cada palabra, y colocando el sufijo `Controller` al resultado. Por ejemplo, el ID del controlador `post-comentarios` corresponde
al nombre de clase de controlador `PostComentarioController`.
Resumen <a name="summary"></a>
-------
En esta sección, has tocado las partes del controlador y la vista del patrón de diseño MVC.
Has creado una acción como parte de un controlador para manejar una petición específica. Y también has creado una vista para armar el contenido de la respuesta. En este simple ejemplo, ningún modelo ha sido involucrado ya que el único dato que fue utilizado fue el parámetro `mensaje`.
También has aprendido acerca de las rutas en Yii, que actúan como puentes entre la petición del usuario y las acciones del controlador.
En la próxima sección, aprenderás como crear un modelo, y agregar una nueva página que contenga un formulario HTML.
...@@ -34,7 +34,7 @@ Structure Application ...@@ -34,7 +34,7 @@ Structure Application
* [Script d'entrée](structure-entry-scripts.md) * [Script d'entrée](structure-entry-scripts.md)
* [Applications](structure-applications.md) * [Applications](structure-applications.md)
* [Composants application](structure-application-components.md) * [Composants application](structure-application-components.md)
* [Controlleurs](structure-controllers.md) * [Contrôleurs](structure-controllers.md)
* [Modèles](structure-models.md) * [Modèles](structure-models.md)
* [Vues](structure-views.md) * [Vues](structure-views.md)
* **TBD** [Filtres](structure-filters.md) * **TBD** [Filtres](structure-filters.md)
...@@ -129,7 +129,7 @@ Services Web RESTful ...@@ -129,7 +129,7 @@ Services Web RESTful
* [Démarrage rapide](rest-quick-start.md) * [Démarrage rapide](rest-quick-start.md)
* [Ressources](rest-resources.md) * [Ressources](rest-resources.md)
* [Controlleurs](rest-controllers.md) * [Contrôleurs](rest-controllers.md)
* [Gestion des routes](rest-routing.md) * [Gestion des routes](rest-routing.md)
* [Formattage des réponses](rest-response-formatting.md) * [Formattage des réponses](rest-response-formatting.md)
* [Authentification](rest-authentication.md) * [Authentification](rest-authentication.md)
......
...@@ -11,7 +11,7 @@ Pour quel usage Yii est il optimal? ...@@ -11,7 +11,7 @@ Pour quel usage Yii est il optimal?
Yii est un framework Web générique, c'est à dire qu'il peut être utilisé pour développer tous types Yii est un framework Web générique, c'est à dire qu'il peut être utilisé pour développer tous types
d'applications Web basées sur PHP. De par son architecture à base de composants et son système de cache sophistiqué, d'applications Web basées sur PHP. De par son architecture à base de composants et son système de cache sophistiqué,
il est particulièrement adapté au développement d'applications a forte audience telles que des portails, des forums, il est particulièrement adapté au développement d'applications à forte audience telles que des portails, des forums,
des systèmes de gestion de contenu (CMS), des sites e-commerce, services Web RESTFul, etc. des systèmes de gestion de contenu (CMS), des sites e-commerce, services Web RESTFul, etc.
......
Повний посібник до 2.0
======================
Даний посібник випущено відповідно до [положень про документацію Yii](http://www.yiiframework.com/doc/terms/).
All Rights Reserved.
2014 © Yii Software LLC.
Введення
--------
* [Про Yii](intro-yii.md)
* [Оновлення із версії 1.1](intro-upgrade-from-v1.md)
Перше знайомство
----------------
* [Встановлення Yii](start-installation.md)
* [Запуск додатка](start-workflow.md)
* [Говоримо «привіт»](start-hello.md)
* [Робота з формами](start-forms.md)
* [Робота з базами даних](start-databases.md)
* [Генерація коду за допомогою Gii](start-gii.md)
* [Що далі?](start-looking-head.md)
Структура додатка
-----------------
* [Огляд](structure-overview.md)
* [Вхідні скрипти](structure-entry-scripts.md)
* [Додатки](structure-applications.md)
* [Компоненти додатка](structure-application-components.md)
* [Контролери](structure-controllers.md)
* [Представлення](structure-views.md)
* [Моделі](structure-models.md)
* **TBD** [Фільтри](structure-filters.md)
* **TBD** [Віджети](structure-widgets.md)
* **TBD** [Модулі](structure-modules.md)
* [Ресурси](structure-assets.md)
* **TBD** [Розширення](structure-extensions.md)
Обробка запитів
---------------
* **TBD** [Bootstrapping](runtime-bootstrapping.md)
* **TBD** [Роутінг](runtime-routing.md)
* **TBD** [Запити](runtime-requests.md)
* **TBD** [Відповіді](runtime-responses.md)
* **TBD** [Сесії та кукі](runtime-sessions-cookies.md)
* [Розбір та генерація URL](runtime-url-handling.md)
* [Обробка помилок](runtime-handling-errors.md)
* [Логування](runtime-logging.md)
Основні поняття
---------------
* [Компоненти](concept-components.md)
* [Властивості](concept-properties.md)
* [Події](concept-events.md)
* [Поведінки](concept-behaviors.md)
* [Конфігурації](concept-configurations.md)
* [Псевдоніми](concept-aliases.md)
* [Автозавантаження класів](concept-autoloading.md)
* [Service Locator](concept-service-locator.md)
* [Dependency Injection Container](concept-di-container.md)
Робота з базами даних
---------------------
* [Обʼєкти доступу до даних (DAO)](db-dao.md) - Зʼєднання з базою даних, прості запити, транзакції і робота зі схемою.
* [Конструктор запитів](db-query-builder.md) - Запити до бази даних через простий шар абстракції.
* [Active Record](db-active-record.md) - Отримання обʼєктів AR, робота з ними та визначення звʼязків.
* [Міграції](db-migrations.md) - Контроль версій схеми даних при роботі в команді.
* **TBD** [Sphinx](db-sphinx.md)
* **TBD** [Redis](db-redis.md)
* **TBD** [MongoDB](db-mongodb.md)
* **TBD** [ElasticSearch](db-elastic-search.md)
Отримання даних від користувача
-------------------------------
* [Створення форм](input-forms.md)
* [Валідація](input-validation.md)
* **TBD** [Завантаження файлів](input-file-uploading.md)
* **TBD** [Робота з декількома моделями](input-multiple-models.md)
Відображення даних
------------------
* **TBD** [Форматування даних](output-formatting.md)
* **TBD** [Посторінкове розбиття](output-pagination.md)
* **TBD** [Сортування](output-sorting.md)
* [Провайдери даних](output-data-providers.md)
* [Віджети для даних](output-data-widgets.md)
* [Темізація](output-theming.md)
Безпека
-------
* [Аутентифікація](security-authentication.md)
* [Авторизація](security-authorization.md)
* [Робота з паролями](security-passwords.md)
* **TBD** [Клієнти авторизації](security-auth-clients.md)
* **TBD** [Кращі практики](security-best-practices.md)
Кешування
---------
* [Огляд](caching-overview.md)
* [Кешуванная даних](caching-data.md)
* [Кешуванная фрагментів](caching-fragment.md)
* [Кешуванная сторінок](caching-page.md)
* [HTTP кешуванная](caching-http.md)
Веб-сервіси REST
----------------
* [Швидкий старт](rest-quick-start.md)
* [Ресурси](rest-resources.md)
* [Контролери](rest-controllers.md)
* [Роутінг](rest-routing.md)
* [Форматування відповіді](rest-response-formatting.md)
* [Аутентифікація](rest-authentication.md)
* [Обмеження кількості запитів](rest-rate-limiting.md)
* [Версіонування](rest-versioning.md)
* [Обробка помилок](rest-error-handling.md)
Інструменти розробника
----------------------
* [Відладочна панель та відладчик](tool-debugger.md)
* [Генерація коду з Gii](tool-gii.md)
* **TBD** [Генератор документації API](tool-api-doc.md)
Тестування
----------
* [Огляд](test-overview.md)
* **TBD** [Модульні тести](test-unit.md)
* **TBD** [Функціональні тести](test-functional.md)
* **TBD** [Приймальні тести](test-acceptance.md)
* [Фікстури](test-fixtures.md)
Розширення Yii
--------------
* [Створення розширень](extend-creating-extensions.md)
* [Розширення коду фреймворку](extend-customizing-core.md)
* [Використання сторонніх бібліотек](extend-using-libs.md)
* **TBD** [Інтеграція Yii в сторонні системи](extend-embedding-in-others.md)
* **TBD** [Одночасне використання Yii 1.1 та 2.0](extend-using-v1-v2.md)
* [Використання Composer](extend-using-composer.md)
Спеціальні теми
---------------
* [Шаблон додатка advanced](tutorial-advanced-app.md)
* [Створення додатка з нуля](tutorial-start-from-scratch.md)
* [Консольні команди](tutorial-console.md)
* [Інтернаціонализація](tutorial-i18n.md)
* [Відправка пошти](tutorial-mailing.md)
* [Вдосконалення продуктивності](tutorial-performance-tuning.md)
* **TBD** [Робота на shared хостингу](tutorial-shared-hosting.md)
* [Шаблонізатори](tutorial-template-engines.md)
Віджети
-------
* GridView: link to demo page
* ListView: link to demo page
* DetailView: link to demo page
* ActiveForm: link to demo page
* Pjax: link to demo page
* Menu: link to demo page
* LinkPager: link to demo page
* LinkSorter: link to demo page
* [Віджети Bootstrap](bootstrap-widgets.md)
* **TBD** [Віджети Jquery UI](jui-widgets.md)
Хелпери
-------
* [Огляд](helper-overview.md)
* **TBD** [ArrayHelper](helper-array.md)
* **TBD** [Html](helper-html.md)
* **TBD** [Url](helper-url.md)
* **TBD** [Security](helper-security.md)
...@@ -193,7 +193,7 @@ Widgets ...@@ -193,7 +193,7 @@ Widgets
* LinkPager: link to demo page * LinkPager: link to demo page
* LinkSorter: link to demo page * LinkSorter: link to demo page
* [Bootstrap Widgets](bootstrap-widgets.md) * [Bootstrap Widgets](bootstrap-widgets.md)
* **TBD** [Jquery UI Widgets](jui-widgets.md) * [Jquery UI Widgets](jui-widgets.md)
Helpers Helpers
......
...@@ -17,7 +17,7 @@ Installation ...@@ -17,7 +17,7 @@ Installation
Yii 2.0 fully embraces [Composer](https://getcomposer.org/), the de facto PHP package manager. Installation Yii 2.0 fully embraces [Composer](https://getcomposer.org/), the de facto PHP package manager. Installation
of the core framework, as well as extensions, are handled through Composer. Please refer to of the core framework, as well as extensions, are handled through Composer. Please refer to
the [Starting from Basic App](start-basic.md) section to learn how to install Yii 2.0. If you want to the [Installing Yii](start-installation.md) section to learn how to install Yii 2.0. If you want to
create new extensions, or turn your existing 1.1 extensions into 2.0-compatible extensions, please refer to create new extensions, or turn your existing 1.1 extensions into 2.0-compatible extensions, please refer to
the [Creating Extensions](extend-creating-extensions.md) section of the guide. the [Creating Extensions](extend-creating-extensions.md) section of the guide.
...@@ -203,7 +203,7 @@ In most cases, you do not need to override [[yii\base\Model::scenarios()|scenari ...@@ -203,7 +203,7 @@ In most cases, you do not need to override [[yii\base\Model::scenarios()|scenari
if the [[yii\base\Model::rules()|rules()]] method fully specifies the scenarios that will exist, and if there is no need to declare if the [[yii\base\Model::rules()|rules()]] method fully specifies the scenarios that will exist, and if there is no need to declare
`unsafe` attributes. `unsafe` attributes.
To learn more details about models, please refer to the [Models](basic-models.md) section. To learn more details about models, please refer to the [Models](structure-models.md) section.
Controllers Controllers
...@@ -270,7 +270,7 @@ be applied to any view file, even a view rendered outside of the context of a co ...@@ -270,7 +270,7 @@ be applied to any view file, even a view rendered outside of the context of a co
Also, there is no more `CThemeManager` component. Instead, `theme` is a configurable property of the `view` Also, there is no more `CThemeManager` component. Instead, `theme` is a configurable property of the `view`
application component. application component.
Please refer to the [Theming](tutorial-theming.md) section for more details. Please refer to the [Theming](output-theming.md) section for more details.
Console Applications Console Applications
...@@ -322,7 +322,7 @@ public function behaviors() ...@@ -322,7 +322,7 @@ public function behaviors()
} }
``` ```
Please refer to the [Filtering](runtime-filtering.md) section for more details. Please refer to the [Filtering](structure-filters.md) section for more details.
Assets Assets
...@@ -336,7 +336,7 @@ By registering an asset bundle via [[yii\web\AssetBundle::register()]], you make ...@@ -336,7 +336,7 @@ By registering an asset bundle via [[yii\web\AssetBundle::register()]], you make
the assets in that bundle accessible via the Web. Unlike in Yii 1, the page registering the bundle will automatically the assets in that bundle accessible via the Web. Unlike in Yii 1, the page registering the bundle will automatically
contain the references to the JavaScript and CSS files specified in that bundle. contain the references to the JavaScript and CSS files specified in that bundle.
Please refer to the [Managing Assets](output-assets.md) section for more details. Please refer to the [Managing Assets](structure-assets.md) section for more details.
Helpers Helpers
...@@ -443,7 +443,7 @@ records by filtering with the primary keys of the primary records. ...@@ -443,7 +443,7 @@ records by filtering with the primary keys of the primary records.
Instead of returning [[yii\db\ActiveRecord|ActiveRecord]] objects, you may chain the [[yii\db\ActiveQuery::asArray()|asArray()]] Instead of returning [[yii\db\ActiveRecord|ActiveRecord]] objects, you may chain the [[yii\db\ActiveQuery::asArray()|asArray()]]
method when building a query to return a large number of records. This will cause the query result to be returned method when building a query to return a large number of records. This will cause the query result to be returned
as arrays, which can significantly reduce the needed CPU time and memory if large number of records . For example, as arrays, which can significantly reduce the needed CPU time and memory if large number of records . For example:
```php ```php
$customers = Customer::find()->asArray()->all(); $customers = Customer::find()->asArray()->all();
...@@ -493,7 +493,7 @@ the same goal. ...@@ -493,7 +493,7 @@ the same goal.
] ]
``` ```
Please refer to the [Url manager docs](url.md) section for more details. Please refer to the [Url manager docs](runtime-url-handling.md) section for more details.
Using Yii 1.1 and 2.x together Using Yii 1.1 and 2.x together
------------------------------ ------------------------------
......
Jquery UI Widgets
=================
> Note: This section is under development.
Out of the box, Yii includes support for the [jQuery UI](http://api.jqueryui.com/) library. jQuery UI is a curated set
of user interface interactions, effects, widgets, and themes built on top of the jQuery JavaScript Library.
Yii widgets
-----------
Most complex jQuery UI components are wrapped into Yii widgets to allow more robust syntax and integrate with
framework features. All widgets belong to `\yii\jui` namespace:
- [[yii\jui\Accordion|Accordion]]
- [[yii\jui\AutoComplete|AutoComplete]]
- [[yii\jui\DatePicker|DatePicker]]
- [[yii\jui\Dialog|Dialog]]
- [[yii\jui\Draggable|Draggable]]
- [[yii\jui\Droppable|Droppable]]
- [[yii\jui\Menu|Menu]]
- [[yii\jui\ProgressBar|ProgressBar]]
- [[yii\jui\Resizable|Resizable]]
- [[yii\jui\Selectable|Selectable]]
- [[yii\jui\Slider|Slider]]
- [[yii\jui\SliderInput|SliderInput]]
- [[yii\jui\Sortable|Sortable]]
- [[yii\jui\Spinner|Spinner]]
- [[yii\jui\Tabs|Tabs]]
\ No newline at end of file
...@@ -2,7 +2,7 @@ Installing Yii ...@@ -2,7 +2,7 @@ Installing Yii
============== ==============
You can install Yii in two ways, using [Composer](http://getcomposer.org/) or by downloading an archive file. You can install Yii in two ways, using [Composer](http://getcomposer.org/) or by downloading an archive file.
The former is the preferred way, as it allows you to install new [extensions](structure-extensions.md) or update Yii by simply running a single command. The former is the preferred way, as it allows you to install new [extensions](extend-creating-extensions.md) or update Yii by simply running a single command.
> Note: Unlike with Yii 1, standard installations of Yii 2 results in both the framework and an application skeleton being downloaded and installed. > Note: Unlike with Yii 1, standard installations of Yii 2 results in both the framework and an application skeleton being downloaded and installed.
......
Widgets
=======
> Note: This section is under development.
Widgets are self-contained building blocks for your views, a way to combine complex logic, display, and functionality into a single component. A widget:
* May contain advanced PHP programming
* Is typically configurable
* Is often provided data to be displayed
* Returns HTML to be shown within the context of the view
There are a good number of widgets bundled with Yii, such as [active form](form.md),
breadcrumbs, menu, and [wrappers around bootstrap component framework](bootstrap-widgets.md). Additionally there are
extensions that provide more widgets, such as the official widget for [jQueryUI](http://www.jqueryui.com) components.
In order to use a widget, your view file would do the following:
```php
// Note that you have to "echo" the result to display it
echo \yii\widgets\Menu::widget(['items' => $items]);
// Passing an array to initialize the object properties
$form = \yii\widgets\ActiveForm::begin([
'options' => ['class' => 'form-horizontal'],
'fieldConfig' => ['inputOptions' => ['class' => 'input-xlarge']],
]);
... form inputs here ...
\yii\widgets\ActiveForm::end();
```
In the first example in the code above, the [[yii\base\Widget::widget()|widget()]] method is used to invoke a widget
that just outputs content. In the second example, [[yii\base\Widget::begin()|begin()]] and [[yii\base\Widget::end()|end()]]
are used for a
widget that wraps content between method calls with its own output. In case of the form this output is the `<form>` tag
with some properties set.
Yii version numbering
=====================
Релізи
------
A.B.C
A = Для Yii2 це завжди 2.
B = Основна версія. Не-BC (`BC`, від англ. Backward compatibility - зворотна сумісність) зміни із інструкціями щодо оновлення.
C = BC зміни та доповнення.
Реліз-кандидати
---------------
A.B.C-rc
A.B.C-rc2
Це коли ми хочемо зробити реліз-кандидат. Номер RC збільшується доки ми не отримаємо стабільний реліз без будь-яких
критичних помилок і звітів про звортню несумісність.
Альфи та бети
-------------
A.B.C-alpha
A.B.C-alpha2
Альфи це є нестабільні версії, де значні помилки можуть і, ймовірно, дійсно будуть.
API ще фіксується і може бути суттєво змінений.
`alpha2` і т.д. можуть або не можуть бути випущені на основі загальної стабільності коду та API.
A.B.C-beta
A.B.C-beta2
Бета більш-менш стабільна із меншою кількістю помилок та меншою нестабільністю API, ніж альфа.
Там все ще можуть бути зміни в API, але на це повинна бути вагома причина.
...@@ -22,4 +22,9 @@ Russian ...@@ -22,4 +22,9 @@ Russian
Spanish Spanish
------- -------
- **Luciano Baraglia** [@lucianobaraglia](https://github.com/lucianobaraglia) - Luciano Baraglia, [@lucianobaraglia](https://github.com/lucianobaraglia)
Ukrainian
---------
- Alexandr Bordun [@borales](https://github.com/Borales), admin@yiiframework.com.ua
\ No newline at end of file
...@@ -30,6 +30,7 @@ $this->beginPage(); ...@@ -30,6 +30,7 @@ $this->beginPage();
<meta charset="<?= Yii::$app->charset ?>"/> <meta charset="<?= Yii::$app->charset ?>"/>
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="language" content="en" /> <meta name="language" content="en" />
<?= Html::csrfMetaTags() ?>
<?php $this->head() ?> <?php $this->head() ?>
<title><?= Html::encode($this->context->pageTitle) ?></title> <title><?= Html::encode($this->context->pageTitle) ?></title>
</head> </head>
......
...@@ -10,7 +10,7 @@ namespace yii\bootstrap; ...@@ -10,7 +10,7 @@ namespace yii\bootstrap;
use yii\web\AssetBundle; use yii\web\AssetBundle;
/** /**
* Bootstrap 2 theme for Bootstrap 3. * Asset bundle for the Twitter bootstrap default theme.
* *
* @author Alexander Makarov <sam@rmcreative.ru> * @author Alexander Makarov <sam@rmcreative.ru>
* @since 2.0 * @since 2.0
......
...@@ -13,6 +13,7 @@ yii\debug\DebugAsset::register($this); ...@@ -13,6 +13,7 @@ yii\debug\DebugAsset::register($this);
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<?= Html::csrfMetaTags() ?>
<title><?= Html::encode($this->title) ?></title> <title><?= Html::encode($this->title) ?></title>
<?php $this->head() ?> <?php $this->head() ?>
</head> </head>
......
...@@ -15,6 +15,7 @@ $asset = yii\gii\GiiAsset::register($this); ...@@ -15,6 +15,7 @@ $asset = yii\gii\GiiAsset::register($this);
<head> <head>
<meta charset="utf-8"/> <meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<?= Html::csrfMetaTags() ?>
<title><?= Html::encode($this->title) ?></title> <title><?= Html::encode($this->title) ?></title>
<?php $this->head() ?> <?php $this->head() ?>
</head> </head>
......
...@@ -45,10 +45,11 @@ Yii Framework 2 Change Log ...@@ -45,10 +45,11 @@ Yii Framework 2 Change Log
- Bug #3752: `QueryBuilder::batchInsert()` does not typecast input values (qiangxue) - Bug #3752: `QueryBuilder::batchInsert()` does not typecast input values (qiangxue)
- Bug #3756: Fix number formatting error for `\yii\base\Formatter` by converting strings to float (kartik-v) - Bug #3756: Fix number formatting error for `\yii\base\Formatter` by converting strings to float (kartik-v)
- Bug #3817: `yii\rbac\PhpManager::getChildren()` returns null instead of expected empty array (qiangxue) - Bug #3817: `yii\rbac\PhpManager::getChildren()` returns null instead of expected empty array (qiangxue)
- Bug #3843: Fixed Menu bug when using `template` with `encodeLabel` => false (creocoder, umneeq)
- Bug #3863: Fixed incorrect js selector for `\yii\widgets\ActiveForm::errorSummaryCssClass` when it contains multiple classes (creocoder, umneeq)
- Bug: Fixed inconsistent return of `\yii\console\Application::runAction()` (samdark) - Bug: Fixed inconsistent return of `\yii\console\Application::runAction()` (samdark)
- Bug: URL encoding for the route parameter added to `\yii\web\UrlManager` (klimov-paul) - Bug: URL encoding for the route parameter added to `\yii\web\UrlManager` (klimov-paul)
- Bug: Fixed the bug that requesting protected or private action methods would cause 500 error instead of 404 (qiangxue) - Bug: Fixed the bug that requesting protected or private action methods would cause 500 error instead of 404 (qiangxue)
- Bug #3843: Fixed Menu bug when using `template` with `encodeLabel` => false (creocoder, umneeq)
- Enh #2264: `CookieCollection::has()` will return false for expired or removed cookies (qiangxue) - Enh #2264: `CookieCollection::has()` will return false for expired or removed cookies (qiangxue)
- Enh #2435: `yii\db\IntegrityException` is now thrown on database integrity errors instead of general `yii\db\Exception` (samdark) - Enh #2435: `yii\db\IntegrityException` is now thrown on database integrity errors instead of general `yii\db\Exception` (samdark)
- Enh #2837: Error page now shows arguments in stack trace method calls (samdark) - Enh #2837: Error page now shows arguments in stack trace method calls (samdark)
...@@ -101,6 +102,7 @@ Yii Framework 2 Change Log ...@@ -101,6 +102,7 @@ Yii Framework 2 Change Log
- Chg #2913: RBAC `DbManager` is now initialized via migration (samdark) - Chg #2913: RBAC `DbManager` is now initialized via migration (samdark)
- Chg #3036: Upgraded Twitter Bootstrap to 3.1.x (qiangxue) - Chg #3036: Upgraded Twitter Bootstrap to 3.1.x (qiangxue)
- Chg #3175: InvalidCallException, InvalidParamException, UnknownMethodException are now extended from SPL BadMethodCallException (samdark) - Chg #3175: InvalidCallException, InvalidParamException, UnknownMethodException are now extended from SPL BadMethodCallException (samdark)
- Chg #3358: Removed automatic CSRF meta tag generation by `View`. Added `Html::csrfMetaTags()` and its call to main layout files (qiangxue)
- Chg #3383: Added `$type` parameter to `IdentityInterface::findIdentityByAccessToken()` (qiangxue) - Chg #3383: Added `$type` parameter to `IdentityInterface::findIdentityByAccessToken()` (qiangxue)
- Chg #3531: \yii\grid\GridView now allows any character (except ":") in the attribute part of the shorthand syntax for columns (rawtaz) - Chg #3531: \yii\grid\GridView now allows any character (except ":") in the attribute part of the shorthand syntax for columns (rawtaz)
- Chg #3544: Added `$key` as a parameter to the callable specified via `yii\grid\DataColumn::value` (mdmunir) - Chg #3544: Added `$key` as a parameter to the callable specified via `yii\grid\DataColumn::value` (mdmunir)
......
...@@ -49,4 +49,7 @@ Upgrade from Yii 2.0 Beta ...@@ -49,4 +49,7 @@ Upgrade from Yii 2.0 Beta
You can add it with `ALTER TABLE log ADD COLUMN prefix TEXT AFTER log_time;`. You can add it with `ALTER TABLE log ADD COLUMN prefix TEXT AFTER log_time;`.
* The `fileinfo` PHP extension is now required by Yii. If you use `yii\helpers\FileHelper::getMimeType()`, make sure * The `fileinfo` PHP extension is now required by Yii. If you use `yii\helpers\FileHelper::getMimeType()`, make sure
you have enabled this extension. This extension is [builtin](http://www.php.net/manual/en/fileinfo.installation.php) in php above `5.3`. you have enabled this extension. This extension is [builtin](http://www.php.net/manual/en/fileinfo.installation.php) in php above `5.3`.
\ No newline at end of file
* Please update your main layout file by adding this line in the `<head>` section: `<?= Html::csrfMetaTags() ?>`.
This change is needed because `yii\web\View` no longer automatically generates CSRF meta tags due to issue #3358.
...@@ -249,6 +249,22 @@ class BaseHtml ...@@ -249,6 +249,22 @@ class BaseHtml
} }
/** /**
* Generates the meta tags containing CSRF token information.
* @return string the generated meta tags
* @see Request::enableCsrfValidation
*/
public static function csrfMetaTags()
{
$request = Yii::$app->getRequest();
if ($request instanceof Request && $request->enableCsrfValidation) {
return static::tag('meta', '', ['name' => 'csrf-param', 'content' => $request->csrfParam]) . "\n "
. static::tag('meta', '', ['name' => 'csrf-token', 'content' => $request->getCsrfToken()]) . "\n";
} else {
return '';
}
}
/**
* Generates a form start tag. * Generates a form start tag.
* @param array|string $action the form action URL. This parameter will be processed by [[Url::to()]]. * @param array|string $action the form action URL. This parameter will be processed by [[Url::to()]].
* @param string $method the form submission method, such as "post", "get", "put", "delete" (case-insensitive). * @param string $method the form submission method, such as "post", "get", "put", "delete" (case-insensitive).
......
...@@ -104,6 +104,7 @@ class Request extends \yii\base\Request ...@@ -104,6 +104,7 @@ class Request extends \yii\base\Request
* *
* In JavaScript, you may get the values of [[csrfParam]] and [[csrfToken]] via `yii.getCsrfParam()` and * In JavaScript, you may get the values of [[csrfParam]] and [[csrfToken]] via `yii.getCsrfParam()` and
* `yii.getCsrfToken()`, respectively. The [[\yii\web\YiiAsset]] asset must be registered. * `yii.getCsrfToken()`, respectively. The [[\yii\web\YiiAsset]] asset must be registered.
* You also need to include CSRF meta tags in your pages by using [[\yii\helpers\Html::csrfMetaTags()]].
* *
* @see Controller::enableCsrfValidation * @see Controller::enableCsrfValidation
* @see http://en.wikipedia.org/wiki/Cross-site_request_forgery * @see http://en.wikipedia.org/wiki/Cross-site_request_forgery
......
...@@ -460,12 +460,6 @@ class View extends \yii\base\View ...@@ -460,12 +460,6 @@ class View extends \yii\base\View
$lines[] = implode("\n", $this->metaTags); $lines[] = implode("\n", $this->metaTags);
} }
$request = Yii::$app->getRequest();
if ($request instanceof \yii\web\Request && $request->enableCsrfValidation && !$request->getIsAjax()) {
$lines[] = Html::tag('meta', '', ['name' => 'csrf-param', 'content' => $request->csrfParam]);
$lines[] = Html::tag('meta', '', ['name' => 'csrf-token', 'content' => $request->getCsrfToken()]);
}
if (!empty($this->linkTags)) { if (!empty($this->linkTags)) {
$lines[] = implode("\n", $this->linkTags); $lines[] = implode("\n", $this->linkTags);
} }
......
...@@ -197,7 +197,7 @@ class ActiveForm extends Widget ...@@ -197,7 +197,7 @@ class ActiveForm extends Widget
protected function getClientOptions() protected function getClientOptions()
{ {
$options = [ $options = [
'errorSummary' => '.' . $this->errorSummaryCssClass, 'errorSummary' => '.' . implode('.', preg_split('/\s+/', $this->errorSummaryCssClass, -1, PREG_SPLIT_NO_EMPTY)),
'validateOnSubmit' => $this->validateOnSubmit, 'validateOnSubmit' => $this->validateOnSubmit,
'errorCssClass' => $this->errorCssClass, 'errorCssClass' => $this->errorCssClass,
'successCssClass' => $this->successCssClass, 'successCssClass' => $this->successCssClass,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment