How to save a model from a form
Let's now look at how to save a model from a form, which could be a new or an updated model.
The steps you need to follow are:
In the
actionmethod, create a new model or get an existing model.In the
actionmethod, check whether there is data in the$_POSTarray.If there is data in
$_POST, fill in theattributesproperty of the model with data from$_POSTand call thesave()method of the model; ifsave()returns true, redirect the user to another page (the details page, for example).
From now on, we will continue to use widgets and helper classes provided by the framework. In this case, the HTML form will be rendered using the yii\widget\ActiveForm class.
The most simple form we can write is the following:
<?php
use yii\widgets\ActiveForm;
$form = ActiveForm::begin([
'id' => 'login-form',
]) ?>
…
…
…
<?php ActiveForm::end() ?>This code generates a form HTML tag with login-form as the id attribute and empty content; the method and...