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:

  1. In the action method, create a new model or get an existing model.
  2. In the action method, check whether there is data in the $_POST array.
  3. If there is data in $_POST, fill in the attributes property of the model with data from $_POST and call the save() method of the model; if save() 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.