Book Image

Yii2 By Example

By : Fabrizio Caldarelli
Book Image

Yii2 By Example

By: Fabrizio Caldarelli

Overview of this book

Yii is a high-performance PHP framework best for developing Web 2.0 applications. It provides fast, secure, and professional features to create robust projects, however, this rapid development requires the ability to organize common tasks together to build a complete application. It's all too easy to get confused; this is where this book comes in. This book contains a series of practical project examples for developers starting from scratch. Each section contains the most relevant theories for every topic as you walk through developing each project, focusing on key aspects that commonly confuse users. The book starts with all the framework’s basic concepts, such as controllers and views, to introduce you to Yii and creating your first application, a simple news reader. You will be learn to configure URL rules to make a pretty URL, essential for search engine optimization. Next, you will walk through Model and ActiveRecord, key concepts in database interaction. The second application you will develop is a reservation system that allows you to manage rooms, customers, and reservations. For this, you will use database connection through SQL and ActiveRecord. More complex than the first one, this application will introduce you to the advanced template of Yii 2, splitting the app into two parts: a frontend for all visitors and a backend for the admin. Finally, you will move on to the last two applications: one that allows connections from remote clients, through RESTful components of Yii 2, and another that creates and organizes automatic tasks using the console application structure of Yii 2.
Table of Contents (20 chapters)
Yii2 By Example
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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