start-forms.md 9 KB
Newer Older
1 2 3
Working with Forms
==================

Larry Ullman committed
4
This section describes how to create a new page with a form for getting data from users.
Qiang Xue committed
5
The page will display a form with a name input field and an email input field.
Larry Ullman committed
6
After getting those two pieces of information from the user, the page will echo the entered values back for confirmation.
Qiang Xue committed
7 8 9 10

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).

Larry Ullman committed
11
Through this tutorial, you will learn how to:
Qiang Xue committed
12

Larry Ullman committed
13 14 15
* Create a [model](structure-models.md) to represent the data entered by a user through a form
* Declare rules to validate the data entered
* Build an HTML form in a [view](structure-views.md)
Qiang Xue committed
16 17


Qiang Xue committed
18
Creating a Model <a name="creating-model"></a>
Qiang Xue committed
19 20
----------------

Larry Ullman committed
21 22
The data to be requested from the user will be represented by an `EntryForm` model class as shown below and
saved in the file `models/EntryForm.php`. Please refer to the [Class Autoloading](concept-autoloading.md)
Qiang Xue committed
23 24 25
section for more details about the class file naming convention.

```php
26 27
<?php

Qiang Xue committed
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
namespace app\models;

use yii\base\Model;

class EntryForm extends Model
{
    public $name;
    public $email;

    public function rules()
    {
        return [
            [['name', 'email'], 'required'],
            ['email', 'email'],
        ];
    }
}
```

Larry Ullman committed
47
The class extends from [[yii\base\Model]], a base class provided by Yii, commonly used to
Qiang Xue committed
48 49
represent form data.

Larry Ullman committed
50
> 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.
Qiang Xue committed
51

Larry Ullman committed
52 53 54 55 56 57
The `EntryForm` class contains two public members, `name` and `email`, which are used to store
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
Qiang Xue committed
58 59

If you have an `EntryForm` object populated with the data entered by a user, you may call
Larry Ullman committed
60
its [[yii\base\Model::validate()|validate()]] to trigger the data validation routines. A data validation
Qiang Xue committed
61 62
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]].
Larry Ullman committed
63 64 65 66 67 68

```php
<?php
$model = new EntryForm();
$model->name = 'Qiang';
$model->email = 'bad';
Qiang Xue committed
69 70 71 72 73
if ($model->validate()) {
    // Good!
} else {
    // Failure!
    // Use $model->getErrors()
Larry Ullman committed
74 75
}
```
Qiang Xue committed
76 77


Qiang Xue committed
78
Creating an Action <a name="creating-action"></a>
Qiang Xue committed
79 80
------------------

Qiang Xue committed
81 82
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.
Qiang Xue committed
83 84

```php
85 86
<?php

Qiang Xue committed
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
namespace app\controllers;

use Yii;
use yii\web\Controller;
use app\models\EntryForm;

class SiteController extends Controller
{
    // ...existing code...

    public function actionEntry()
    {
        $model = new EntryForm;

        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            // valid data received in $model

            // do something meaningful here about $model ...

            return $this->render('entry-confirm', ['model' => $model]);
        } else {
            // either the page is initially displayed or there is some validation error
            return $this->render('entry', ['model' => $model]);
        }
    }
}
```

The action first creates an `EntryForm` object. It then tries to populate the model
Larry Ullman committed
116
with the data from `$_POST`, provided in Yii by [[yii\web\Request::post()]].
Qiang Xue committed
117 118
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.
Qiang Xue committed
119

Larry Ullman committed
120 121 122
If everything is fine, the action will render a view named `entry-confirm` to confirm the data entered 
with the user that the data entered. If a problem occurred, the `entry` view will
be rendered, wherein the HTML form  will be shown, along with any validation error messages.
Qiang Xue committed
123

Larry Ullman committed
124 125
> 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) that 
Qiang Xue committed
126
  provides components such as `request`, `response`, `db`, etc. to support specific functionality.
Larry Ullman committed
127
  In the above code, the `request` component of the application instance is used to access the `$_POST` data.
Qiang Xue committed
128 129


Qiang Xue committed
130
Creating Views <a name="creating-views"></a>
Qiang Xue committed
131 132
--------------

Larry Ullman committed
133 134
Finally, create two view files named `entry-confirm` and `entry`. These will be rendered by the `entry` action,
as just described.
Qiang Xue committed
135

Larry Ullman committed
136
The `entry-confirm` view simply displays the name and email data. It should be stored in the file `views/site/entry-confirm.php`.
Qiang Xue committed
137 138 139 140 141 142 143 144 145 146 147 148 149

```php
<?php
use yii\helpers\Html;
?>
<p>You have entered the following information:</p>

<ul>
    <li><label>Name</label>: <?= Html::encode($model->name) ?></li>
    <li><label>Email</label>: <?= Html::encode($model->email) ?></li>
</ul>
```

Larry Ullman committed
150
The `entry` view displays an HTML form. It should be stored in the file `views/site/entry.php`.
Qiang Xue committed
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170

```php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
?>
<?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'name') ?>

    <?= $form->field($model, 'email') ?>

    <div class="form-group">
        <?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
    </div>

<?php ActiveForm::end(); ?>
```

The view uses a powerful [widget](structure-widgets.md) called [[yii\widgets\ActiveForm|ActiveForm]] to
Larry Ullman committed
171
build the HTML form. The `begin()` and `end()` methods of the widget render the opening and closing
Qiang Xue committed
172
form tags, respectively. Between the two method calls, input fields are created by the
Larry Ullman committed
173 174
[[yii\widgets\ActiveForm::field()|field()]] method. The first input field is for the "name" data,
and the second for the "email" data. After the input fields, the [[yii\helpers\Html::submitButton()]] method
Qiang Xue committed
175 176 177
is called to generate a submit button.


Qiang Xue committed
178 179
Trying it Out <a name="trying-it-out"></a>
-------------
Qiang Xue committed
180

Qiang Xue committed
181 182 183 184 185 186
To see how it works, use your browser to access the following URL:

```
http://hostname/index.php?r=site/entry
```

Larry Ullman committed
187 188
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
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.
Qiang Xue committed
189

190 191
![Form with Validation Errors](images/start-form-validation.png)

Qiang Xue committed
192 193 194
After entering a valid name and email address and clicking the submit button, you will see a new page
displaying the data that you just entered.

195 196 197
![Confirmation of Data Entry](images/start-entry-confirmation.png)


Qiang Xue committed
198

Qiang Xue committed
199
### Magic Explained <a name="magic-explained"></a>
Qiang Xue committed
200 201 202 203 204

You may wonder how the HTML form works behind the scene, because it seems almost magical that it can
display a label for each input field and show error messages if you do not enter the data correctly
without reloading the page.

Larry Ullman committed
205
Yes, the data validation is initially done on the client side using JavaScript, and secondarily performed on the server side via PHP.
Qiang Xue committed
206
[[yii\widgets\ActiveForm]] is smart enough to extract the validation rules that you have declared in `EntryForm`,
Larry Ullman committed
207
turn them into executable JavaScript code, and use the JavaScript to perform data validation. In case you have disabled
Qiang Xue committed
208 209 210
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.

Qiang Xue committed
211 212
> Warning: Client-side validation is a convenience that provides for a better user experience. Server-side validation
  is always required, whether or not client-side validation is in place.
Larry Ullman committed
213 214 215 216 217

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 
Qiang Xue committed
218 219 220 221 222 223 224 225
the following code:

```php
<?= $form->field($model, 'name')->label('Your Name') ?>
<?= $form->field($model, 'email')->label('Your Email') ?>
```

> Info: Yii provides many such widgets to help you quickly build complex and dynamic views.
Larry Ullman committed
226
  As you will learn later, writing a new widget is also extremely easy. You may want to turn much of your
Qiang Xue committed
227 228 229
  view code into reusable widgets to simplify view development in future.


Qiang Xue committed
230
Summary <a name="summary"></a>
Qiang Xue committed
231
-------
Qiang Xue committed
232

Larry Ullman committed
233 234
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 said data.
Qiang Xue committed
235

Larry Ullman committed
236 237
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, but Yii provides powerful widgets
Qiang Xue committed
238 239
to make this task very easy.

Larry Ullman committed
240
In the next section, you will learn how to work with databases, which are needed in nearly every application.