# How to Program With Yii2: Working With the Database and Active Record (ok)

<figure><img src="/files/gdN7B2tDTidBURpS0YBm" alt=""><figcaption></figcaption></figure>

C:\xampp74\htdocs\oectest\migrations\m230311\_041200\_create\_status\_table.php

```php
<?php
use yii\db\Migration;
use yii\db\Schema;
/**
 * Handles the creation of table `{{%status}}`.
 */
class m230311_041200_create_status_table extends Migration {
	/**
	 * {@inheritdoc}
	 */
	public function safeUp() {
		$tableOptions = null;
		if ($this->db->driverName === 'mysql') {
			$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
		}
		$this->createTable('{{%status}}', [
			'id' => Schema::TYPE_PK,
			'message' => Schema::TYPE_TEXT . ' NOT NULL DEFAULT ""',
			'permissions' => Schema::TYPE_SMALLINT . ' NOT NULL DEFAULT 0',
			'created_at' => Schema::TYPE_INTEGER . ' NOT NULL',
			'updated_at' => Schema::TYPE_INTEGER . ' NOT NULL',
		], $tableOptions);
	}

	/**
	 * {@inheritdoc}
	 */
	public function safeDown() {
		$this->dropTable('{{%status}}');
	}
}

```

<figure><img src="/files/6CuIRwzdd19nWQrYUvid" alt=""><figcaption></figcaption></figure>

C:\xampp74\htdocs\oectest\models\Status.php

```php
<?php
namespace app\models;
use Yii;
/**
 * This is the model class for table "status".
 *
 * @property integer $id
 * @property string $message
 * @property integer $permissions
 * @property integer $created_at
 * @property integer $updated_at
 */
class Status extends \yii\db\ActiveRecord
{
	const PERMISSIONS_PRIVATE = 10;
	const PERMISSIONS_PUBLIC = 20;
	/**
	 * @inheritdoc
	 */
	public static function tableName()
	{
		return 'status';
	}
	/**
	 * @inheritdoc
	 */
	public function rules()
	{
		return [
			[['message', 'created_at', 'updated_at'], 'required'],
			[['message'], 'string'],
			[['permissions', 'created_at', 'updated_at'], 'integer'],
		];
	}
	/**
	 * @inheritdoc
	 */
	public function attributeLabels()
	{
		return [
			'id' => 'ID',
			'message' => 'Message',
			'permissions' => 'Permissions',
			'created_at' => 'Created At',
			'updated_at' => 'Updated At',
		];
	}
	public function getPermissions()
	{
		return array(self::PERMISSIONS_PRIVATE => 'Private', self::PERMISSIONS_PUBLIC => 'Public');
	}
	public function getPermissionsLabel($permissions)
	{
		if ($permissions == self::PERMISSIONS_PUBLIC) {
			return 'Public';
		} else {
			return 'Private';
		}
	}
}

```

C:\xampp74\htdocs\oectest\controllers\StatusController.php

```php
<?php
namespace app\controllers;
use app\models\Status;
use app\models\StatusSearch;
use Yii;
use yii\filters\VerbFilter;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
/**
 * StatusController implements the CRUD actions for Status model.
 */
class StatusController extends Controller
{
	public function behaviors()
	{
		return [
			'verbs' => [
				'class' => VerbFilter::className(),
				'actions' => [
					'delete' => ['post'],
				],
			],
		];
	}
	/**
	 * Lists all Status models.
	 * @return mixed
	 */
	public function actionIndex()
	{
		$searchModel = new StatusSearch();
		$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
		return $this->render('index', [
			'searchModel' => $searchModel,
			'dataProvider' => $dataProvider,
		]);
	}
	/**
	 * Displays a single Status model.
	 * @param integer $id
	 * @return mixed
	 */
	public function actionView($id)
	{
		return $this->render('view', [
			'model' => $this->findModel($id),
		]);
	}
	/**
	 * Creates a new Status model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 * @return mixed
	 */
	public function actionCreate()
	{
		$model = new Status();
		if ($model->load(Yii::$app->request->post())) {
			$model->created_at = time();
			$model->updated_at = time();
			if ($model->save()) {
				return $this->redirect(['view', 'id' => $model->id]);
			}
		}
		return $this->render('create', [
			'model' => $model,
		]);
	}
	/**
	 * Updates an existing Status model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id
	 * @return mixed
	 */
	public function actionUpdate($id)
	{
		$model = $this->findModel($id);
		if ($model->load(Yii::$app->request->post()) && $model->save()) {
			return $this->redirect(['view', 'id' => $model->id]);
		} else {
			return $this->render('update', [
				'model' => $model,
			]);
		}
	}
	/**
	 * Deletes an existing Status model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 * @param integer $id
	 * @return mixed
	 */
	public function actionDelete($id)
	{
		$this->findModel($id)->delete();
		return $this->redirect(['index']);
	}
	/**
	 * Finds the Status model based on its primary key value.
	 * If the model is not found, a 404 HTTP exception will be thrown.
	 * @param integer $id
	 * @return Status the loaded model
	 * @throws NotFoundHttpException if the model cannot be found
	 */
	protected function findModel($id)
	{
		if (($model = Status::findOne($id)) !== null) {
			return $model;
		} else {
			throw new NotFoundHttpException('The requested page does not exist.');
		}
	}
}

```

C:\xampp74\htdocs\oectest\views\layouts\main.php

```php
<?php
/** @var yii\web\View $this */
/** @var string $content */
use app\assets\AppAsset;
use app\widgets\Alert;
use yii\bootstrap5\Breadcrumbs;
use yii\bootstrap5\Html;
use yii\bootstrap5\Nav;
use yii\bootstrap5\NavBar;
AppAsset::register($this);
$this->registerCsrfMetaTags();
$this->registerMetaTag(['charset' => Yii::$app->charset], 'charset');
$this->registerMetaTag(['name' => 'viewport', 'content' => 'width=device-width, initial-scale=1, shrink-to-fit=no']);
$this->registerMetaTag(['name' => 'description', 'content' => $this->params['meta_description'] ?? '']);
$this->registerMetaTag(['name' => 'keywords', 'content' => $this->params['meta_keywords'] ?? '']);
$this->registerLinkTag(['rel' => 'icon', 'type' => 'image/x-icon', 'href' => Yii::getAlias('@web/favicon.ico')]);
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>" class="h-100">
<head>
  <title><?= Html::encode($this->title) ?></title>
  <?php $this->head() ?>
</head>
<body class="d-flex flex-column h-100">
  <?php $this->beginBody() ?>
  <header id="header">
    <?php
    NavBar::begin([
      'brandLabel' => Yii::$app->name,
      'brandUrl' => Yii::$app->homeUrl,
      'options' => ['class' => 'navbar-expand-md navbar-dark bg-dark fixed-top'],
    ]);
    echo Nav::widget([
      'options' => ['class' => 'navbar-nav navbar-right'],
      'items' => [
        ['label' => 'Home', 'url' => ['/site/index']],
        ['label' => 'Status', 'url' => ['/status/index']],
        ['label' => 'About', 'url' => ['/site/about']],
        ['label' => 'Contact', 'url' => ['/site/contact']],
        Yii::$app->user->isGuest ? ['label' => 'Login', 'url' => ['/site/login']] : ['label' => 'Logout (' . Yii::$app->user->identity->username . ')', 'url' => ['/site/logout'], 'linkOptions' => ['data-method' => 'post']],
      ],
    ]);
    NavBar::end();
    ?>
  </header>
  <main id="main" class="flex-shrink-0" role="main">
    <div class="container">
      <?php if (!empty($this->params['breadcrumbs'])) : ?>
        <?= Breadcrumbs::widget(['links' => $this->params['breadcrumbs']]) ?>
      <?php endif ?>
      <?= Alert::widget() ?>
      <?= $content ?>
    </div>
  </main>
  <footer id="footer" class="mt-auto py-3 bg-light">
    <div class="container">
      <div class="row text-muted">
        <div class="col-md-6 text-center text-md-start">&copy; My Company <?= date('Y') ?></div>
        <div class="col-md-6 text-center text-md-end"><?= Yii::powered() ?></div>
      </div>
    </div>
  </footer>
  <?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>

```

C:\xampp74\htdocs\oectest\views\status\_form.php

```php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model app\models\Status */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="status-form">
  <?php $form = ActiveForm::begin(); ?>
  <?= $form->field($model, 'message')->textarea(['rows' => 6]) ?>
  <?=
  $form->field($model, 'permissions')->dropDownList(
    $model->getPermissions(),
    ['prompt' => '- Choose Your Permissions -']
  ) ?>
  <div class="form-group">
    <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
  </div>
  <?php ActiveForm::end(); ?>
</div>

```

C:\xampp74\htdocs\oectest\views\status\create.php

```php
<?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model app\models\Status */
$this->title = 'Create Status';
$this->params['breadcrumbs'][] = ['label' => 'Statuses', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="status-create">
  <h1><?= Html::encode($this->title) ?></h1>
  <?= $this->render('_form', [
    'model' => $model,
  ]) ?>
</div>

```

C:\xampp74\htdocs\oectest\views\status\index.php

```php
<?php
use yii\helpers\Html;
use yii\grid\GridView;
/* @var $this yii\web\View */
/* @var $searchModel app\models\StatusSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Statuses';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="status-index">
  <h1><?= Html::encode($this->title) ?></h1>
  <?php // echo $this->render('_search', ['model' => $searchModel]);
  ?>
  <p>
    <?= Html::a('Create Status', ['create'], ['class' => 'btn btn-success']) ?>
  </p>
  <?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
      ['class' => 'yii\grid\SerialColumn'],
      'id',
      'message:ntext',
      'permissions',
      'created_at',
      'updated_at',
      ['class' => 'yii\grid\ActionColumn'],
    ],
  ]); ?>
</div>

```

C:\xampp74\htdocs\oectest\views\status\update.php

```php
<?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model app\models\Status */
$this->title = 'Update Status: ' . ' ' . $model->id;
$this->params['breadcrumbs'][] = ['label' => 'Statuses', 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => $model->id, 'url' => ['view', 'id' => $model->id]];
$this->params['breadcrumbs'][] = 'Update';
?>
<div class="status-update">
  <h1><?= Html::encode($this->title) ?></h1>
  <?= $this->render('_form', [
    'model' => $model,
  ]) ?>
</div>

```

C:\xampp74\htdocs\oectest\views\status\view\.php

```php
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
/* @var $this yii\web\View */
/* @var $model app\models\Status */
$this->title = $model->id;
$this->params['breadcrumbs'][] = ['label' => 'Statuses', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="status-view">
  <h1><?= Html::encode($this->title) ?></h1>
  <p>
    <?= Html::a('Update', ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?>
    <?= Html::a('Delete', ['delete', 'id' => $model->id], ['class' => 'btn btn-danger', 'data' => ['confirm' => 'Are you sure you want to delete this item?', 'method' => 'post',]]) ?>
  </p>
  <?= DetailView::widget([
    'model' => $model,
    'attributes' => [
      'id',
      'message:ntext',
      'permissions',
      'created_at',
      'updated_at',
    ]
  ]) ?>
</div>

```

{% embed url="<https://oec.test/index.php?r=status/view&id=1>" %}

<figure><img src="/files/0IPNDN6AfXfYSMOR35Aj" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/cZQfTAA3RKp6Fss3FlMs" alt=""><figcaption></figcaption></figure>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://pdo.gitbook.io/lear-yii/how-to-program-with-yii2-working-with-the-database-and-active-record-ok.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
