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
action
method, create a new model or get an existing model.In the
action
method, check whether there is data in the$_POST
array.If there is data in
$_POST
, fill in theattributes
property of the model with data from$_POST
and 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...