How to create new forms in Yii 2

Hi guys, In this tutorial I will explain to you how you can create new forms in Yii 2. I will follow the Yii 2 documentation.

To create a new form in Yii 2, you must

  • Create a new model called models/EntryForm.php.
  • In your created model, add this code:

namespace app\models;

 

use yii\base\Model;

 

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

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

  • Next, add new action in your controller:

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]);
}
}

  • Don't forget to add use app\models\EntryForm; in your controller.
  • Create a new php file in your views folder: views/site/entry-confirm.php
  • And add this code:

<?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>

  • This page will display the submitted data.
  • Next, create a new php file in your views folder: views/site/entry.php
  • And add this code:

<?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(); ?>

  • This page will display the forms.
  • Now, go to http://localhost/yii/web/index.php?r=site%2Fentry

An you will see your created form!

Video tutorial:

In this way you can easily create your contact forms or other forms with Yii 2!









Leave a Comment