1. Code
  2. PHP
  3. Yii

How to Program With Yii2: Working With the Database and Active Record

Scroll to top
This post is part of a series called How to Program With Yii2.
How to Program With Yii2: Exploring MVC, Forms and Layouts
How to Program With Yii2: Working With the Database and Active Record
Final product imageFinal product imageFinal product image
What You'll Be Creating

If you're asking, "What's Yii?" check out my earlier tutorial: Introduction to the Yii Framework, which reviews the benefits of Yii and includes an overview of what's new in Yii 2.0, released October 12, 2014.

In Programming with Yii2: Getting Started, we set up Yii2 locally, built a Hello World application, set up a remote server and used GitHub to deploy our code. In part two, we learned about Yii's implementation of its Model View Controller architecture and how to build web pages and forms that collect and validate data. In this tutorial, we'll use Yii's database and active record capabilities to automate code generation for a basic web application.

For these examples, we'll continue to imagine we're building a framework for posting simple status updates, e.g. our own mini-Twitter.

1. Creating Your Database

First, we need to create a database in our development environment. I do this through MAMP's PHPMyAdmin web user interface. Navigate to PHPMyAdmin, e.g. http://localhost:8888/MAMP/index.php?page=phpmyadmin, choose the Databases tab and create a database called hello:

MAMP PHPMyAdmin Create DatabaseMAMP PHPMyAdmin Create DatabaseMAMP PHPMyAdmin Create Database

You can also use the MySQL command line interface.

Now, we'll provide database credentials to Yii's database configuration file. Open /hello/config/db.php and provide your MySQL database credentials. Mine look like this:

1
<?php
2
3
return [
4
    'class' => 'yii\db\Connection',
5
    'dsn' => 'mysql:host=localhost;dbname=hello',
6
    'username' => 'root',
7
    'password' => 'password',
8
    'charset' => 'utf8',
9
];

Now, we'll create our first database migration. A migration provides a programmatic way to create and update database schemas. It's especially helpful if you're running on multiple servers or in different environments. It eliminates the difficulty of importing SQL scripts.

For our coding examples, you can use the Git repository from the last tutorial to follow along, or you can download the completed repository here.

Create the Migration

Our first migration will create the Status table. Open Terminal and enter the following:

1
cd ~/Sites/hello
2
./yii migrate/create create_status_table

It should look like this, when you're done:

Yii Migration CreateYii Migration CreateYii Migration Create

When you open \hello\migrations, you'll see a file named similar to m141201_013120_create_status_table.php. It should look like this when opened:

1
<?php
2
3
use yii\db\Schema;
4
use yii\db\Migration;
5
6
class m141201_013120_create_status_table extends Migration
7
{
8
    public function up()
9
    {
10
11
    }
12
13
    public function down()
14
    {
15
        echo "m141201_013120_create_status_table cannot be reverted.\n";
16
17
        return false;
18
    }
19
}

This is the default migration code that Yii provides. Next, we'll update it to provide the fields we need.

Building the Status Table

Our Status table will store message text and specify whether a post is private or public. Each row will also have an id, create and update time fields.

Update your migration code to ours:

1
public function up()
2
    {
3
          $tableOptions = null;
4
          if ($this->db->driverName === 'mysql') {
5
              $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
6
          }
7
8
          $this->createTable('{{%status}}', [
9
              'id' => Schema::TYPE_PK,
10
              'message' => Schema::TYPE_TEXT.' NOT NULL DEFAULT ""',
11
              'permissions' => Schema::TYPE_SMALLINT . ' NOT NULL DEFAULT 0',
12
              'created_at' => Schema::TYPE_INTEGER . ' NOT NULL',
13
              'updated_at' => Schema::TYPE_INTEGER . ' NOT NULL',
14
          ], $tableOptions);
15
      }
16
17
18
    public function down()
19
    {
20
      $this->dropTable('{{%status}}');
21
    }

Notice how we've added definitions for the fields we need such as message, permissions, created_at, and updated_at.

Run the Migration

To tell Yii to create the table, we need to run the migration. It's easy. From Terminal again, we run ./yii migrate/up:

1
$ ./yii migrate/up
2
Yii Migration Tool (based on Yii v2.0.0)
3
4
Total 1 new migration to be applied:
5
    m141201_013120_create_status_table
6
7
Apply the above migration? (yes|no) [no]:yes
8
*** applying m141201_013120_create_status_table
9
    > create table {{%status}} ... done (time: 0.032s)
10
*** applied m141201_013120_create_status_table (time: 0.038s)
11
12
13
Migrated up successfully.

If you browse the table using PHPMyAdmin, you should see something like this:

PHPMyAdmin View the Status TablePHPMyAdmin View the Status TablePHPMyAdmin View the Status Table

Now that we've created the database table, we can begin to use Gii, Yii's powerful scaffolding generator, to automate all of the model view controller code.

2. Using Gii: The Yii Code Generator

Gii is Yii's scaffolding code generator. It uses its knowledge of your database schema to generate well-written, default model view controller code for your application. Gii can turn a database schema into a basic working web application in minutes. It's incredibly powerful. Let me show you how it works.

Building the Model

With Gii, we start by building a model based on each database table we've created. For our example, we'll use the Status table.

To begin using Gii, navigate to your web application and add /gii, e.g. http://localhost:8888/hello/web/gii. You'll see something like this:

Yiis Gii Scaffolding GeneratorYiis Gii Scaffolding GeneratorYiis Gii Scaffolding Generator

Click on Model Generator, and enter status in the Table Name field:

Gii Model GeneratorGii Model GeneratorGii Model Generator

When you click Preview, it will show you which files it will build. Since we already have a Status.php model file from the last tutorial, click Overwrite. Then, click Generate.

Gii Model Generator PreviewGii Model Generator PreviewGii Model Generator Preview

The results will look like this:

Gii Model Code GeneratedGii Model Code GeneratedGii Model Code Generated

Open the /hello/models/Status.php file and you'll see the basic validation rules and form attributes which Yii has built for us:

1
<?php
2
3
namespace app\models;
4
5
use Yii;
6
7
/**

8
 * This is the model class for table "status".

9
 *

10
 * @property integer $id

11
 * @property string $message

12
 * @property integer $permissions

13
 * @property integer $created_at

14
 * @property integer $updated_at

15
 */
16
class Status extends \yii\db\ActiveRecord
17
{
18
    /**

19
     * @inheritdoc

20
     */
21
    public static function tableName()
22
    {
23
        return 'status';
24
    }
25
26
    /**

27
     * @inheritdoc

28
     */
29
    public function rules()
30
    {
31
        return [
32
            [['message', 'created_at', 'updated_at'], 'required'],
33
            [['message'], 'string'],
34
            [['permissions', 'created_at', 'updated_at'], 'integer']
35
        ];
36
    }
37
38
    /**

39
     * @inheritdoc

40
     */
41
    public function attributeLabels()
42
    {
43
        return [
44
            'id' => 'ID',
45
            'message' => 'Message',
46
            'permissions' => 'Permissions',
47
            'created_at' => 'Created At',
48
            'updated_at' => 'Updated At',
49
        ];
50
    }
51
}

Building the Web Interface

Now, it's time to use Gii to build the controller and views for the Status table. Return to the Gii home page and click CRUD Generator, e.g. http://localhost:8888/hello/web/gii/crud:

For Model Class, enter app\models\Status (these entries are case sensitive). For Search Model Class, enter app\models\StatusSearch. For Controller Class, enter app\controllers\StatusController. It should look like this:

Yiis Gii CRUD GeneratorYiis Gii CRUD GeneratorYiis Gii CRUD Generator

Click Preview. You'll see the following—be sure to click Overwrite again since we have older files from the last tutorial which need to be updated:

Yiis Gii CRUD Generator PreviewYiis Gii CRUD Generator PreviewYiis Gii CRUD Generator Preview

When you click Generate, you'll see all of the controller and view files generated:

Yiis Gii CRUD Generated CodeYiis Gii CRUD Generated CodeYiis Gii CRUD Generated Code

The Default CRUD Pages

Navigate your browser to http://localhost:8888/hello/web/status, and you'll see the generated CRUD index page. Since there aren't any rows in the database yet, it'll appear empty.

Yiis Gii CRUD Generated Index GridYiis Gii CRUD Generated Index GridYiis Gii CRUD Generated Index Grid

Now, click on Create Status and you'll see the default Create Status Form which Gii created:

Yii Default Form for Status TableYii Default Form for Status TableYii Default Form for Status Table

It's pretty amazing how quickly Gii creates working code for us. Next, we'll customize the scaffolding code to make this work for us.

3. Customizing Our Code

Customizing the Form View

Let's clean up the form. In /hello/views/Status/_form.php, remove the created and updated fields:

1
    <?= $form->field($model, 'created_at')->textInput() ?>
2
    <?= $form->field($model, 'updated_at')->textInput() ?>

Replace the permissions field with the drop-down list code we created in part two of this series:

1
<?=
2
    $form->field($model, 'permissions')->dropDownList($model->getPermissions(), 
3
             ['prompt'=>'- Choose Your Permissions -']) ?>

We need to put the getPermissions function back in the model as well. Edit /hello/models/Status.php. Put back the constant definitions and permissions functions:

1
      const PERMISSIONS_PRIVATE = 10;
2
      const PERMISSIONS_PUBLIC = 20;  
3
...
4
5
public function getPermissions() {
6
      return array (self::PERMISSIONS_PRIVATE=>'Private',self::PERMISSIONS_PUBLIC=>'Public');
7
    }
8
    
9
    public function getPermissionsLabel($permissions) {
10
      if ($permissions==self::PERMISSIONS_PUBLIC) {
11
        return 'Public';
12
      } else {
13
        return 'Private';        
14
      }
15
    }

Your new Status form should look like this:

Revised Status Create FormRevised Status Create FormRevised Status Create Form

We need to adjust the controller a bit to make the form save properly.

Customizing the Controller

In /hello/controllers/StatusController.php, replace the actionCreate method with this code:

1
public function actionCreate()
2
    {
3
        $model = new Status();
4
5
        if ($model->load(Yii::$app->request->post())) {
6
          $model->created_at = time();
7
          $model->updated_at = time();
8
           if ($model->save()) {             
9
             return $this->redirect(['view', 'id' => $model->id]);             
10
           } 
11
        } 
12
        return $this->render('create', [
13
            'model' => $model,
14
        ]);
15
    }

When the form is posted, we manually set the created_at and updated_at fields, then we save the data in the database. 

When you save your first status update, you'll see the following view page:

Default Status ViewDefault Status ViewDefault Status View

Adjusting the Layout

Let's readjust the navbar so that it doesn't drop down for Status but jumps directly to the Status index page. Edit /hello/views/layouts/main.php and replace the Nav::widget code with this:

1
echo Nav::widget([
2
                'options' => ['class' => 'navbar-nav navbar-right'],
3
                'items' => [
4
                    ['label' => 'Home', 'url' => ['/site/index']],
5
                    ['label' => 'Status', 'url' => ['/status/index']],
6
                    ['label' => 'About', 'url' => ['/site/about']],
7
                    ['label' => 'Contact', 'url' => ['/site/contact']],
8
                    Yii::$app->user->isGuest ?
9
                        ['label' => 'Login', 'url' => ['/site/login']] :
10
                        ['label' => 'Logout (' . Yii::$app->user->identity->username . ')',
11
                            'url' => ['/site/logout'],
12
                            'linkOptions' => ['data-method' => 'post']],
13
                ],
14
            ]);

The Grid View

When you return to the Status index view, you can see the Yii2 Grid filled with data:

Default Grid View with DataDefault Grid View with DataDefault Grid View with Data

The code which generates this page is in /hello/views/status/index.php:

1
<?php
2
3
use yii\helpers\Html;
4
use yii\grid\GridView;
5
6
/* @var $this yii\web\View */
7
/* @var $searchModel app\models\StatusSearch */
8
/* @var $dataProvider yii\data\ActiveDataProvider */
9
10
$this->title = 'Statuses';
11
$this->params['breadcrumbs'][] = $this->title;
12
?>
13
<div class="status-index">
14
15
    <h1><?= Html::encode($this->title) ?></h1>
16
    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

17
18
    <p>
19
        <?= Html::a('Create Status', ['create'], ['class' => 'btn btn-success']) ?>
20
    </p>
21
22
    <?= GridView::widget([
23
        'dataProvider' => $dataProvider,
24
        'filterModel' => $searchModel,
25
        'columns' => [
26
            ['class' => 'yii\grid\SerialColumn'],
27
28
            'id',
29
            'message:ntext',
30
            'permissions',
31
            'created_at',
32
            'updated_at',
33
34
            ['class' => 'yii\grid\ActionColumn'],
35
        ],
36
    ]); ?>
37
38
</div>

If you try out the column sorting and view, update and delete icons, you'll see that Gii has built out all the functionality for these features as well.

So in just a few minutes, we created a schema for our database, and generated a model and all of the web application code needed for a basic application. I hope you've found Yii's code generation capabilities as impressive as I have.

What's Next?

Next up, I'll show you how to integrate user registration and login capabilities into our application so we can set up join relations between status posts and specific users.

If you'd like to know when the next Yii2 tutorial arrives, follow me @reifman on Twitter or check my Tuts+ instructor page. My instructor page will include all the articles from this series as soon as they are published.

Related Links

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.