Commit 5e56bc5f by Larry Ullman

Edited

parent 9a77807b
Working with Forms Working with Forms
================== ==================
In this section, we will describe how to create a new page to get data from users. This section describes how to create a new page with a form for getting data from users.
The page will display a form with a name input field and an email input field. The page will display a form with a name input field and an email input field.
After getting these data from a user, the page will echo them back to the user for confirmation. After getting those two pieces of information from the user, the page will echo the entered values back for confirmation.
To achieve this goal, besides creating an [action](structure-controllers.md) and To achieve this goal, besides creating an [action](structure-controllers.md) and
two [views](structure-views.md), you will also create a [model](structure-models.md). two [views](structure-views.md), you will also create a [model](structure-models.md).
Through this tutorial, you will learn Through this tutorial, you will learn how to:
* How to create a [model](structure-models.md) to represent the data entered by a user; * Create a [model](structure-models.md) to represent the data entered by a user through a form
* How to declare rules to validate the data entered by users; * Declare rules to validate the data entered
* How to build an HTML form in a [view](structure-views.md). * Build an HTML form in a [view](structure-views.md)
Creating a Model <a name="creating-model"></a> Creating a Model <a name="creating-model"></a>
---------------- ----------------
To represent the data entered by a user, create an `EntryForm` model class as shown below and The data to be requested from the user will be represented by an `EntryForm` model class as shown below and
save the class in the file `models/EntryForm.php`. Please refer to the [Class Autoloading](concept-autoloading.md) saved in the file `models/EntryForm.php`. Please refer to the [Class Autoloading](concept-autoloading.md)
section for more details about the class file naming convention. section for more details about the class file naming convention.
```php ```php
...@@ -44,26 +44,38 @@ class EntryForm extends Model ...@@ -44,26 +44,38 @@ class EntryForm extends Model
} }
``` ```
The class extends from [[yii\base\Model]], a base class provided by Yii that is commonly used to The class extends from [[yii\base\Model]], a base class provided by Yii, commonly used to
represent form data. represent form data.
The class contains two public members, `name` and `email`, which are used to keep > Info: [[yii\base\Model]] is used as a parent for model classes *not* associated with database tables. [[yii\db\ActiveRecord]] is normally the parent for model classes that do correspond to database tables.
the data entered by the user. It also contains a method named `rules()` which returns a set
of rules used for validating the data. The validation rules declared above state that
* both the `name` and `email` data are required; The `EntryForm` class contains two public members, `name` and `email`, which are used to store
* the `email` data must be a valid email address. the data entered by the user. It also contains a method named `rules()`, which returns a set
of rules for validating the data. The validation rules declared above state that
* both the `name` and `email` values are required
* the `email` data must be a syntactically valid email address
If you have an `EntryForm` object populated with the data entered by a user, you may call If you have an `EntryForm` object populated with the data entered by a user, you may call
its [[yii\base\Model::validate()|validate()]] to trigger the data validation. A data validation its [[yii\base\Model::validate()|validate()]] to trigger the data validation routines. A data validation
failure will turn on the [[yii\base\Model::hasErrors|hasErrors]] property, and through failure will set the [[yii\base\Model::hasErrors|hasErrors]] property to true, and you may learn what validation errors occurred through [[yii\base\Model::getErrors|errors]].
[[yii\base\Model::getErrors|errors]] you may learn what validation errors the model has.
```php
<?php
$model = new EntryForm();
$model->name = 'Qiang';
$model->email = 'bad';
if ($model->validate()) { // Good!
} else { // Failure!
// Use $model->getErrors()
}
```
Creating an Action <a name="creating-action"></a> Creating an Action <a name="creating-action"></a>
------------------ ------------------
Next, create an `entry` action in the `site` controller, like you did in the previous section. Next, you'll need to create an `entry` action in the `site` controller that will use the new model. The process of creating and using actions was explained in the [Saying Hello](start-hello.md) section.
```php ```php
<?php <?php
...@@ -97,28 +109,26 @@ class SiteController extends Controller ...@@ -97,28 +109,26 @@ class SiteController extends Controller
``` ```
The action first creates an `EntryForm` object. It then tries to populate the model The action first creates an `EntryForm` object. It then tries to populate the model
with the data from `$_POST` which is provided in Yii through [[yii\web\Request::post()]]. with the data from `$_POST`, provided in Yii by [[yii\web\Request::post()]].
If the model is successfully populated (i.e., the user has submitted the HTML form), If the model is successfully populated (i.e., if the user has submitted the HTML form), the action will call [[yii\base\Model::validate()|validate()]] to make sure the values entered are valid.
it will call [[yii\base\Model::validate()|validate()]] to make sure the data entered
are valid.
If everything is fine, the action will render a view named `entry-confirm` to confirm If everything is fine, the action will render a view named `entry-confirm` to confirm the data entered
with the user that the data he has entered is accepted. Otherwise, the `entry` view will with the user that the data entered. If a problem occurred, the `entry` view will
be rendered, which will show the HTML form together with the validation error messages (if any). be rendered, wherein the HTML form will be shown, along with any validation error messages.
> Info: The expression `Yii::$app` represents the [application](structure-applications.md) instance > Info: The expression `Yii::$app` represents the [application](structure-applications.md) instance,
which is a globally accessible singleton. It is also a [service locator](concept-service-locator.md) which is a globally accessible singleton. It is also a [service locator](concept-service-locator.md) that
providing components, such as `request`, `response`, `db`, etc. to support specific functionalities. provides components such as `request`, `response`, `db`, etc. to support specific functionality.
In the above code, the `request` component is used to access the `$_POST` data. In the above code, the `request` component of the application instance is used to access the `$_POST` data.
Creating Views <a name="creating-views"></a> Creating Views <a name="creating-views"></a>
-------------- --------------
Finally, create two views named `entry-confirm` and `entry` that are rendered by the `entry` action, Finally, create two view files named `entry-confirm` and `entry`. These will be rendered by the `entry` action,
as described in the last subsection. as just described.
The `entry-confirm` view simply displays the name and email data. It should be stored as the file `views/site/entry-confirm.php`. The `entry-confirm` view simply displays the name and email data. It should be stored in the file `views/site/entry-confirm.php`.
```php ```php
<?php <?php
...@@ -132,7 +142,7 @@ use yii\helpers\Html; ...@@ -132,7 +142,7 @@ use yii\helpers\Html;
</ul> </ul>
``` ```
The `entry` view displays an HTML form. It should be stored as the file `views/site/entry.php`. The `entry` view displays an HTML form. It should be stored in the file `views/site/entry.php`.
```php ```php
<?php <?php
...@@ -153,10 +163,10 @@ use yii\widgets\ActiveForm; ...@@ -153,10 +163,10 @@ use yii\widgets\ActiveForm;
``` ```
The view uses a powerful [widget](structure-widgets.md) called [[yii\widgets\ActiveForm|ActiveForm]] to The view uses a powerful [widget](structure-widgets.md) called [[yii\widgets\ActiveForm|ActiveForm]] to
build the HTML form. The `begin()` and `end()` methods of the widget render the opening and close build the HTML form. The `begin()` and `end()` methods of the widget render the opening and closing
form tags, respectively. Between the two method calls, input fields are created by the form tags, respectively. Between the two method calls, input fields are created by the
[[yii\widgets\ActiveForm::field()|field()]] method. The first input field is about the "name" data, [[yii\widgets\ActiveForm::field()|field()]] method. The first input field is for the "name" data,
and the second the "email" data. After the input fields, the [[yii\helpers\Html::submitButton()]] method and the second for the "email" data. After the input fields, the [[yii\helpers\Html::submitButton()]] method
is called to generate a submit button. is called to generate a submit button.
...@@ -169,10 +179,8 @@ To see how it works, use your browser to access the following URL: ...@@ -169,10 +179,8 @@ To see how it works, use your browser to access the following URL:
http://hostname/index.php?r=site/entry http://hostname/index.php?r=site/entry
``` ```
You will see a page displaying a form with two input fields. In front of each input field, a label You will see a page displaying a form with two input fields. In front of each input field, a label indicates what data is to be entered. If you click the submit button without
is also displayed indicating what data you need to enter. If you click the submit button without entering anything, or if you do not provide a valid email address, you will see an error message displayed next to each problematic input field.
entering anything, or if you do not provide a valid email address, you will see an error message that
is displayed next to each problematic input field.
![Form with Validation Errors](images/start-form-validation.png) ![Form with Validation Errors](images/start-form-validation.png)
...@@ -189,14 +197,18 @@ You may wonder how the HTML form works behind the scene, because it seems almost ...@@ -189,14 +197,18 @@ You may wonder how the HTML form works behind the scene, because it seems almost
display a label for each input field and show error messages if you do not enter the data correctly display a label for each input field and show error messages if you do not enter the data correctly
without reloading the page. without reloading the page.
Yes, the data validation is actually done on the client side using JavaScript as well as on the server side. Yes, the data validation is initially done on the client side using JavaScript, and secondarily performed on the server side via PHP.
[[yii\widgets\ActiveForm]] is smart enough to extract the validation rules that you have declared in `EntryForm`, [[yii\widgets\ActiveForm]] is smart enough to extract the validation rules that you have declared in `EntryForm`,
turn them into JavaScript code, and use the JavaScript to perform data validation. In case you have disabled turn them into executable JavaScript code, and use the JavaScript to perform data validation. In case you have disabled
JavaScript on your browser, the validation will still be performed on the server side, as shown in JavaScript on your browser, the validation will still be performed on the server side, as shown in
the `actionEntry()` method. This ensures data validity in all circumstances. the `actionEntry()` method. This ensures data validity in all circumstances.
The labels for input fields are generated by the `field()` method based on the model property names. > Warning: Client-side validation is a conveniences that provides for a better user experience. Server-side validation is always required, whether or not client-side validation is in place.
For example, the label `Name` will be generated for the `name` property. You may customize a label by
The labels for input fields are generated by the `field()` method, using the property names from the model.
For example, the label `Name` will be generated for the `name` property.
You may customize a label within a view using
the following code: the following code:
```php ```php
...@@ -205,18 +217,18 @@ the following code: ...@@ -205,18 +217,18 @@ the following code:
``` ```
> Info: Yii provides many such widgets to help you quickly build complex and dynamic views. > Info: Yii provides many such widgets to help you quickly build complex and dynamic views.
As you will learn later, writing a new widget is also extremely easy. You may turn much of your As you will learn later, writing a new widget is also extremely easy. You may want to turn much of your
view code into reusable widgets to simplify view development in future. view code into reusable widgets to simplify view development in future.
Summary <a name="summary"></a> Summary <a name="summary"></a>
------- -------
In this section, you have touched every part in the MVC design pattern. You have learned how In this section of the guide, you have touched every part in the MVC design pattern. You have learned how
to create a model class to represent the user data and validate them. to create a model class to represent the user data and validate said data.
You have also learned how to get data from users and how to display them back. This is a task that You have also learned how to get data from users and how to display data back in the browser. This is a task that
could take you a lot of time when developing an application. Yii provides powerful widgets could take you a lot of time when developing an application, but Yii provides powerful widgets
to make this task very easy. to make this task very easy.
In the next section, you will learn how to work with databases which are needed in nearly every application. In the next section, you will learn how to work with databases, which are needed in nearly every application.
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