start-forms.md 9.34 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.

Qiang Xue committed
50 51
> 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
52

Larry Ullman committed
53 54 55 56 57 58
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
59 60

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

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


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

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

```php
86 87
<?php

Qiang Xue committed
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 116
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
117
with the data from `$_POST`, provided in Yii by [[yii\web\Request::post()]].
Qiang Xue committed
118 119
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
120

Larry Ullman committed
121
> Info: The expression `Yii::$app` represents the [application](structure-applications.md) instance,
Qiang Xue committed
122
  which is a globally accessible singleton. It is also a [service locator](concept-service-locator.md) that
Qiang Xue committed
123
  provides components such as `request`, `response`, `db`, etc. to support specific functionality.
Larry Ullman committed
124
  In the above code, the `request` component of the application instance is used to access the `$_POST` data.
Qiang Xue committed
125

Carsten Brandt committed
126 127
If everything is fine, the action will render a view named `entry-confirm` to confirm the successful submission
of the data to the user. If no data is submitted or the data contains errors, the `entry` view will
Qiang Xue committed
128 129 130 131 132 133
be rendered, wherein the HTML form will be shown, along with any validation error messages.

> Note: In this very simple example we just render the confirmation page upon valid data submission. In practice,
  you should consider using [[yii\web\Controller::refresh()|refresh()]] or [[yii\web\Controller::redirect()|redirect()]]
  to avoid [form resubmission problems](http://en.wikipedia.org/wiki/Post/Redirect/Get).

Qiang Xue committed
134

Qiang Xue committed
135
Creating Views <a name="creating-views"></a>
Qiang Xue committed
136 137
--------------

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

Larry Ullman committed
141
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
142 143 144 145 146 147 148 149 150 151 152 153 154

```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
155
The `entry` view displays an HTML form. It should be stored in the file `views/site/entry.php`.
Qiang Xue committed
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175

```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
176
build the HTML form. The `begin()` and `end()` methods of the widget render the opening and closing
Qiang Xue committed
177
form tags, respectively. Between the two method calls, input fields are created by the
Larry Ullman committed
178 179
[[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
180 181 182
is called to generate a submit button.


Qiang Xue committed
183 184
Trying it Out <a name="trying-it-out"></a>
-------------
Qiang Xue committed
185

Qiang Xue committed
186 187 188 189 190 191
To see how it works, use your browser to access the following URL:

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

Larry Ullman committed
192 193
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
194

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

Qiang Xue committed
197 198 199
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.

200 201 202
![Confirmation of Data Entry](images/start-entry-confirmation.png)


Qiang Xue committed
203

Qiang Xue committed
204
### Magic Explained <a name="magic-explained"></a>
Qiang Xue committed
205 206 207 208 209

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
210
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
211
[[yii\widgets\ActiveForm]] is smart enough to extract the validation rules that you have declared in `EntryForm`,
Larry Ullman committed
212
turn them into executable JavaScript code, and use the JavaScript to perform data validation. In case you have disabled
Qiang Xue committed
213 214 215
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
216 217
> 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
218 219 220 221 222

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
223 224 225 226 227 228 229 230
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
231
  As you will learn later, writing a new widget is also extremely easy. You may want to turn much of your
Qiang Xue committed
232 233 234
  view code into reusable widgets to simplify view development in future.


Qiang Xue committed
235
Summary <a name="summary"></a>
Qiang Xue committed
236
-------
Qiang Xue committed
237

Larry Ullman committed
238 239
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
240

Larry Ullman committed
241 242
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
243 244
to make this task very easy.

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