arrow_back
Back

Yii2 ActiveForm: models, validation, and form rendering

Andrew Dorokhov Andrew Dorokhov schedule 2 min read
menu_book Table of Contents

The main way to work with forms in Yii is the yii\widgets\ActiveForm widget. Use it whenever a form is backed by a model.

The model can be based on either of these classes:

  • yii\base\Model — when the form is not tied to a database table.
  • yii\db\ActiveRecord — when it is.

Form model

For a standalone form, extend Model and declare the attributes as public properties:

namespace app\models;

use yii\base\Model;

class ContactForm extends Model
{
    public $name;
    public $email;
    public $subject;
    public $body;

    public function attributeLabels()
    {
        return [
            'name' => 'Your name',
            'email' => 'Your email address',
            'subject' => 'Subject',
            'body' => 'Content',
        ];
    }
}

For a model bound to a table, generate the Active Record class with Gii.

Rendering the form

<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;

$form = ActiveForm::begin([
    'id' => 'login-form',
    'options' => ['class' => 'form-horizontal'],
]) ?>
    <?= $form->field($model, 'username') ?>
    <?= $form->field($model, 'password')->passwordInput() ?>

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

The action is given as a route and converted to a URL automatically:

$form = ActiveForm::begin([
    'id'     => 'new-spreadsheet-form',
    'action' => ['add'],
]); ?>

Form fields (ActiveField)

Without extra parameters you get a text input (input type="text"):

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

To customise the field, chain ActiveField methods:

// Password input:
$form->field($model, 'password')->passwordInput();

// A hint and a custom label:
echo $form->field($model, 'username')->textInput()->hint('Please enter your name')->label('Name');

// An HTML5 email input:
echo $form->field($model, 'email')->input('email');

// No label:
echo $form->field($model, 'username')->label(false);

Placeholder

<?= $form->field($model, 'url')->textInput(['placeholder' => 'https://docs.google.com/spreadsheets/d/...']); ?>

AJAX submission

An example of submitting an ActiveForm over AJAX: open_in_new riptutorial.com .

code

Need Help with Development?

Happy to help — reach out via the contacts or go straight to my Upwork profile.

work View Upwork Profile arrow_forward
Next Article

Yii2 GridView: columns, DataProvider, filters, and pagination

arrow_forward