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 ...
Get Yii2 By Example now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.