1

Create CRUD in yii2 without GII

DEMO HERE

Screenshot from 2015-08-05 23:00:00

Previously, i wrote an article “How to create CRUD using GII in Yii2“.
Now here i will show you how to Create CRUD without GII.

Let’s begin !

CONFIGURATION

1) First, we must setting database connection.
Open file common/config/main-local.php

config database connection yii2

CREATE TABLE & INSERT RECORD

1) Create a table “student” with this structure below :
structure table student

2) Insert 4 record like this :
insert record phpmyadmin

CREATE MVC

Models

1) Create a model “Student.php” in /frontend/models/Student.php.
Copy the following script :

<?php
namespace app\models;

use Yii;

class Student extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'student';
    }
    
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['full_name', 'address', 'phone'], 'required'],
            [['full_name', 'address'], 'string', 'max' => 100],
            [['phone'], 'string', 'max' => 15]
        ];
    }    
}

– To create a model, we must using \yii\db\ActiveRecord

– Look function tableName(), put your table name to that function.

– Function rules() used for filtering your input.
If you using ‘required’ like above, then the input (full_name, address, phone) must be filled.
‘max’ => 100 is script to limit the characters that you input.

Controllers & Views

Create

2) Next create a controller “StudentController.php” in /frontend/controllers/StudentController.php.
Copy script below :

<?php
namespace frontend\controllers;

use Yii;
use app\models\Student;
use yii\web\Controller;

/**
 * manual CRUD
 **/
class StudentController extends Controller
{	
	/**
	 * Create
	 */
	public function actionCreate()
	{
		$model = new Student();

		// new record
		if($model->load(Yii::$app->request->post()) && $model->save()){
			return $this->redirect(['index']);
		}
				
		return $this->render('create', ['model' => $model]);
	}
}

– namespace is a way of encapsulating items.
– use app\models\Student; this script used for call your model in /frontend/models/Student.php

3) Create folder “student” in /frontend/views/student, then create a file “create.php” inside “student” folder.
Copy this script :

<?= $this->render('_form', [
	'model' => $model,
]) ?>

Next, create a file “_form.php”
Copy the following script :

<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
?>

<?php $form = ActiveForm::begin(); ?>

	<?= $form->field($model, 'full_name'); ?>
	<?= $form->field($model, 'address'); ?>
	<?= $form->field($model, 'phone'); ?>
	
	<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']); ?>

<?php ActiveForm::end(); ?>

Screenshot from 2015-08-05 22:41:48

4) Now, try to insert a new record :

http://localhost/yii2_advanced/frontend/web/index.php?r=student/create

insert a new record in yii2

READ

1) Add the action “actionIndex” in “StudentContoller.php”

<?php
namespace frontend\controllers;

use Yii;
use app\models\Student;
use yii\web\Controller;

/**
 * manual CRUD
 **/
class StudentController extends Controller
{	
	/**
	 * Create
	 */
	public function actionCreate()
	{
		$model = new Student();

		// new record
		if($model->load(Yii::$app->request->post()) && $model->save()){
			return $this->redirect(['index']);
		}
				
		return $this->render('create', ['model' => $model]);
	}
	
	/**
	 * Read
	 */
	public function actionIndex()
	{
		$student = Student::find()->all();
		
		return $this->render('index', ['model' => $student]);
	}
}

2) Create a file “index.php” inside “student” folder. And copy the following script :

<?php
use yii\helpers\Html;
?>

<style>
table th,td{
	padding: 10px;
}
</style>

<?= Html::a('Create', ['student/create'], ['class' => 'btn btn-success']); ?>

<table border="1">
	<tr>
		<th>Full_name</th>
		<th>Address</th>
		<th>Phone</th>
		<th>Action</th>
	</tr>
	<?php foreach($model as $field){ ?>
	<tr>
		<td><?= $field->full_name; ?></td>
		<td><?= $field->address; ?></td>
		<td><?= $field->phone; ?></td>
		<td><?= Html::a("Edit", ['student/edit', 'id' => $field->id]); ?> | <?= Html::a("Delete", ['student/delete', 'id' => $field->id]); ?></td>
	</tr>
	<?php } ?>
</table>

Screenshot from 2015-08-05 22:57:06

3) Try to read record :
read record yii2

Update

1) Update “StudentController.php” with adding the action “actionEdit”.
Copy the script below :

<?php
namespace frontend\controllers;

use Yii;
use app\models\Student;
use yii\web\Controller;
use yii\web\NotFoundHttpException;

/**
 * manual CRUD
 **/
class StudentController extends Controller
{	
	/**
	 * Create
	 */
	public function actionCreate()
	{
		$model = new Student();

		// new record
		if($model->load(Yii::$app->request->post()) && $model->save()){
			return $this->redirect(['index']);
		}
				
		return $this->render('create', ['model' => $model]);
	}
	
	/**
	 * Read
	 */
	public function actionIndex()
	{
		$student = Student::find()->all();
		
		return $this->render('index', ['model' => $student]);
	}
	
	/**
	 * Edit
	 * @param integer $id
	 */
	public function actionEdit($id)
	{
		$model = Student::find()->where(['id' => $id])->one();

		// $id not found in database
		if($model === null)
			throw new NotFoundHttpException('The requested page does not exist.');
		
		// update record
		if($model->load(Yii::$app->request->post()) && $model->save()){
			return $this->redirect(['index']);
		}
		
		return $this->render('edit', ['model' => $model]);
	}	
}

2) Create a file “edit.php” inside “student” folder. Copy the script below :

<?= $this->render('_form', [
	'model' => $model,
]) ?>

Screenshot from 2015-08-05 23:05:39

3) Try to edit record :
update record in yii2

Delete

1) The last, we create function to delete record.
Still in “StudentController.php”, add the action “actionDelete”. And Copy the following script :

<?php

namespace frontend\controllers;

use Yii;
use app\models\Student;
use yii\web\Controller;
use yii\web\NotFoundHttpException;

/**
 * manual CRUD
 **/
class StudentController extends Controller
{	
	/**
	 * Create
	 */
	public function actionCreate()
	{
		$model = new Student();

		// new record
		if($model->load(Yii::$app->request->post()) && $model->save()){
			return $this->redirect(['index']);
		}
				
		return $this->render('create', ['model' => $model]);
	}
	
	/**
	 * Read
	 */
	public function actionIndex()
	{
		$student = Student::find()->all();
		
		return $this->render('index', ['model' => $student]);
	}
	
	/**
	 * Edit
	 * @param integer $id
	 */
	public function actionEdit($id)
	{
		$model = Student::find()->where(['id' => $id])->one();

		// $id not found in database
		if($model === null)
			throw new NotFoundHttpException('The requested page does not exist.');
		
		// update record
		if($model->load(Yii::$app->request->post()) && $model->save()){
			return $this->redirect(['index']);
		}
		
		return $this->render('edit', ['model' => $model]);
	}
	
	/**
	 * Delete
	 * @param integer $id
	 */
	 public function actionDelete($id)
	 {
		 $model = Student::findOne($id);
		
		// $id not found in database
		if($model === null)
			throw new NotFoundHttpException('The requested page does not exist.');
			
		// delete record
		$model->delete();
		
		return $this->redirect(['index']);
	 }	
}

2) You can access url below to delete a record :

http://localhost/yii2_advanced/frontend/web/index.php?r=student/edit&id=1

 
 
FINISH!!

Ambar Hasbiyatmoko

Hello, I'm web developer. Passionate about programming, web server, and networking.

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload the CAPTCHA.