Yii 2 Examples on Using Forms and Fields

Yii 2 Examples on Using Forms and Fields

Last updated:

There's been some changes in the way you deal with form elements in Yii 2 (in comparison with Yii 1) so here are some examples to get you started:

Create an ActiveForm with a single field (text input) and a submit button on a view

(assuming you have a valid $model Model with the suitable attributes)

<?php $form = ActiveForm::begin(['id' => 'my-form']); ?>
<?= $form->field($model, 'name') ?>
<?= Html::submitButton('Submit') ?>
<?php ActiveForm::end(); ?>

Set custom config options for your fields - for example a text input and a textarea

<?php $form = ActiveForm::begin(['id' => 'my-other-form']); ?>
<?= $form->field($model, 'name')->textInput(['tabIndex'=>'2','id'=>'first-name']) ?>
<?= $form->field($model, 'description')->textArea(['rows' => '6']) ?>
<?= Html::submitButton('Submit') ?>
<?php ActiveForm::end(); ?>

Dialogue & Discussion