input-forms.md 5.54 KB
Newer Older
1 2
Creating Forms
==============
3

4
The primary way of using forms in Yii is through [[yii\widgets\ActiveForm]]. This approach should be preferred when
5
the form is based upon a model. Additionally, there are some useful methods in [[yii\helpers\Html]] that are typically
6
used for adding buttons and help text to any form.
7

8
A form, that is displayed on the client side, will in most cases have a corresponding [model](structure-models.md) which is used
9 10 11 12 13
to validate its input on the server side (Check the [Validating Input](input-validation.md) section for more details on validation).
When creating model-based forms, the first step is to define the model itself. The model can be either based upon
an [Active Record](db-active-record.md) class, representing some data from the database, or a generic Model class
(extending from [[yii\base\Model]]) to capture arbitrary input, for example a login form.
In the following example we show, how a generic Model is used for a login form:
14 15

```php
16
<?php
17

18
class LoginForm extends \yii\base\Model
19
{
20 21 22 23 24 25
    public $username;
    public $password;

    public function rules()
    {
        return [
26
            // define validation rules here
27 28
        ];
    }
29 30 31
}
```

32 33
In the controller, we will pass an instance of that model to the view, wherein the [[yii\widgets\ActiveForm|ActiveForm]]
widget is used to display the form:
34 35

```php
36
<?php
37 38 39
use yii\helpers\Html;
use yii\widgets\ActiveForm;

40
$form = ActiveForm::begin([
41 42
    'id' => 'login-form',
    'options' => ['class' => 'form-horizontal'],
43
]) ?>
44 45 46 47 48 49 50 51
    <?= $form->field($model, 'username') ?>
    <?= $form->field($model, 'password')->passwordInput() ?>

    <div class="form-group">
        <div class="col-lg-offset-1 col-lg-11">
            <?= Html::submitButton('Login', ['class' => 'btn btn-primary']) ?>
        </div>
    </div>
52 53 54
<?php ActiveForm::end() ?>
```

55 56
In the above code, [[yii\widgets\ActiveForm::begin()|ActiveForm::begin()]] not only creates a form instance, but also marks the beginning of the form.
All of the content placed between [[yii\widgets\ActiveForm::begin()|ActiveForm::begin()]] and
57
[[yii\widgets\ActiveForm::end()|ActiveForm::end()]] will be wrapped within the HTML `<form>` tag.
58 59
As with any widget, you can specify some options as to how the widget should be configured by passing an array to
the `begin` method. In this case, an extra CSS class and identifying ID are passed to be used in the opening `<form>` tag.
60
For all available options, please refer to the API documentation of [[yii\widgets\ActiveForm]].
61

62
In order to create a form element in the form, along with the element's label, and any applicable JavaScript validation,
63 64 65
the [[yii\widgets\ActiveForm::field()|ActiveForm::field()]] method is called, which returns an instance of [[yii\widgets\ActiveField]].
When the result of this method is echoed directly, the result is a regular (text) input.
To customize the output, you can chain additional methods of [[yii\widgets\ActiveField|ActiveField]] to this call:
66 67

```php
68
// a password input
69
<?= $form->field($model, 'password')->passwordInput() ?>
70
// adding a hint and a customized label
71
<?= $form->field($model, 'username')->textInput()->hint('Please enter your name')->label('Name') ?>
72
// creating a HTML5 email input element
73 74 75
<?= $form->field($model, 'email')->input('email') ?>
```

76
This will create all the `<label>`, `<input>` and other tags according to the [[yii\widgets\ActiveField::$template|template]] defined by the form field.
77 78
The name of the input field is determined automatically from the model's [[yii\base\Model::formName()|form name] and the attribute's name.
For example, the name for the input field for the `username` attribute in the above example will be `LoginForm[username]`. This naming rule will result in an array
79 80
of all attributes for the login form to be available in `$_POST['LoginForm']` on the server side.

Carsten Brandt committed
81
Specifying the attribute of the model can be done in more sophisticated ways. For example when an attribute may
82 83 84 85 86
take an array value when uploading multiple files or selecting multiple items you may specify it by appending `[]`
to the attribute name:

```php
// allow multiple files to be uploaded:
ff committed
87
echo $form->field($model, 'uploadFile[]')->fileInput(['multiple'=>'multiple']);
88 89 90 91 92

// allow multiple items to be checked:
echo $form->field($model, 'items[]')->checkboxList(['a' => 'Item A', 'b' => 'Item B', 'c' => 'Item C']);
```

93
Additional HTML tags can be added to the form using plain HTML or using the methods from the [[yii\helpers\Html|Html]]-helper
94 95 96 97 98 99 100 101 102
class like it is done in the above example with [[yii\helpers\Html::submitButton()|Html::submitButton()]].


> Tip: If you are using Twitter Bootstrap CSS in your application you may want to use
> [[yii\bootstrap\ActiveForm]] instead of [[yii\widgets\ActiveForm]], which is an extension of the
> ActiveForm class that adds some additional styling that works well with the bootstrap CSS framework.


> Tip: in order to style required fields with asterisk you can use the following CSS:
103
>
104 105 106 107 108 109 110
> ```css
> div.required label:after {
>     content: " *";
>     color: red;
> }
> ```

111 112
The next section [Validating Input](input-validation.md) handles the validation of the submitted form data on the server
side as well as ajax- and client side validation.
113

114
To read about more complex usage of forms, you may want to check out the following sections:
115

116 117 118
- [Collecting tabular input](input-tabular-input.md) for collecting data for multiple models of the same kind.
- [Complex Forms with Multiple Models](input-multiple-models.md) for handling multiple different models in the same form.
- [Uploading Files](input-file-upload) on how to use forms for uploading files.