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

https://code.tutsplus.com/tutorials/how-to-program-with-yii2-working-with-the-database-and-active-record--cms-22768

C:\xampp74\htdocs\oectest\migrations\m230311_041200_create_status_table.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}}');
	}
}

C:\xampp74\htdocs\oectest\models\Status.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
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
/** @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
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
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
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
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
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>

Last updated