Yii CRUD

Yii provides a gii tool which is a code generator tool. It gives you the generated code for CRUD. We'll learn how to generate CRUD with gii.

A simple example is shown here to generate a crud. We have named the Yii2 folder as crud. And our table name is employees.

# Step 1 Open Gii

In the browser, type the following, http://localhost/crud/frontend/web/index.php?r=gii

YII 2 Curd 1

# Step 2 Generate Model

YII 2 Curd 2

Look at the above snapshot, enter the table name which is employees in our case. Employees model class will be generated. Scroll down the page and click on Preview button.

YII 2 Curd 3

Look at the above snpashot, click on Generate button to generate the code.

YII 2 Curd 4

You'll see a successfull message as shown above.


# Step 2 Generate CRUD

YII 2 Curd 5

Look at the above snapshot,

In Model class, file Employees with the path frontend\models\Employees is generated.

In Search Model class, file EmployeesSearch with the path frontend\controllers\EmployeesSearch is generated.

In Controller class, file EmployeesController with the path @frontend\views\Employees is generated.

Click on Preview button to check for error. If no error is there, click on Generate button to generaate the code. Again you'll get a succesfull message for code generation.

Now our CRUD has been succesfully generated. To check it, run it on browser with the URL http://localhost/crud/frontend/web/index.php?r=employees/

YII 2 Curd 6

Look at the above snapshot, Employees is our table name and you can search an entry from this table.

To insert values in the table click on Create Employees button. Following page will appear.

YII 2 Curd 7

Fill the details above, and click on Create button. Data will be inserted in the table employees.

YII 2 Curd 8

Look at the above snapshot, we have filled some entries in the table. Here you can see the icons to View, Update and Delete.

On clicking View icon, following page containing John's information will appear.

YII 2 Curd 9

On clicking Update icon, following page containing John's information will appear where you can edit anything. Click on Update button after making changes.

YII 2 Curd 10

On clicking Delete icon, following box will appear asking you to delete it or not.

YII 2 Curd 11

# Generated Code

In controllers, file EmployeesController.php will have the following code.


<?php 

namespace frontend\controllers; 

use Yii; 
use frontend\models\Employees; 
use frontend\models\EmployeesSearch; 
use yii\web\Controller; 
use yii\web\NotFoundHttpException; 
use yii\filters\VerbFilter; 

/** 
 * EmployeesController implements the CRUD actions for Employees model. 
 */ 
class EmployeesController extends Controller 
{ 
    /** 
     * @inheritdoc 
     */ 
    public function behaviors() 
    { 
        return [ 
            'verbs' => [ 
                'class' => VerbFilter::className(), 
 'actions' => [ 
                    'delete' => ['POST'], 
                ], 
            ], 
        ]; 
    } 

    /** 
     * Lists all Employees models. 
     * @return mixed 
     */ 
    public function actionIndex() 
    { 
        $searchModel = new EmployeesSearch(); 
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams); 

        return $this->render('index', [ 
            'searchModel' => $searchModel, 
            'dataProvider' => $dataProvider, 
        ]); 
    } 

    /** 
     * Displays a single Employees model. 
     * @param integer $id 
     * @return mixed 
     */ 
    public function actionView($id) 
    { 
        return $this->render('view', [ 
            'model' => $this->findModel($id), 
        ]); 
    } 

    /** 
     * Creates a new Employees model. 
     * If creation is successful, the browser will be redirected to the 'view' page. 
     * @return mixed 
     */ 
    public function actionCreate() 
    { 
        $model = new Employees(); 

        if ($model->load(Yii::$app->request->post()) && $model->save()) { 
            return $this->redirect(['view', 'id' => $model->id]); 
        } else { 
            return $this->render('create', [ 
                'model' => $model, 
            ]); 
        } 
    } 
            
/** 
     * Updates an existing Employees 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 Employees 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 Employees model based on its primary key value. 
     * If the model is not found, a 404 HTTP exception will be thrown. 
     * @param integer $id 
     * @return Employees the loaded model 
     * @throws NotFoundHttpException if the model cannot be found 
     */ 
    protected function findModel($id) 
    { 
        if (($model = Employees::findOne($id)) !== null) { 
            return $model; 
        } else { 
            throw new NotFoundHttpException('The requested page does not exist.'); 
        } 
    } 
}  

In models, file Employees.php will have the following code.


<?php 

namespace frontend\models; 

use Yii; 

/** 
 * This is the model class for table "employees". 
 * 
 * @property integer $id 
 * @property string $name 
 * @property string $designation 
 * @property integer $contact 
 * @property string $email 
 */ 
class Employees extends \yii\db\ActiveRecord 
{ 
    /** 
     * @inheritdoc 
     */ 
    public static function tableName() 
    { 
        return 'employees'; 
    } 

    /** 
     * @inheritdoc 
     */ 
    public function rules() 
    { 
        return [ 
            [['name', 'designation', 'contact', 'email'], 'required'], 
            [['contact'], 'integer'], 
            [['name'], 'string', 'max' => 20], 
            [['designation'], 'string', 'max' => 50], 
            [['email'], 'string', 'max' => 80], 
        ]; 
    } 

    /** 
     * @inheritdoc 
     */ 
    public function attributeLabels() 
    { 
        return [ 
            'id' => 'ID', 
            'name' => 'Name', 
            'designation' => 'Designation', 
            'contact' => 'Contact', 
            'email' => 'Email', 
       ]; 
    } 
} 
In models, file EmployeesSearch.php will have the following code.

<?php 

namespace frontend\models; 

use Yii; 
use yii\base\Model; 
use yii\data\ActiveDataProvider; 
use frontend\models\Employees; 

/** 
 * EmployeesSearch represents the model behind the search form about `frontend\models\Employees`. 
 */ 
class EmployeesSearch extends Employees 
{ 
    /** 
     * @inheritdoc 
     */ 
    public function rules() 
    { 
        return [ 
            [['id', 'contact'], 'integer'], 
            [['name', 'designation', 'email'], 'safe'], 
        ]; 
    } 

    /** 
     * @inheritdoc 
     */ 
    public function scenarios() 
    { 
        // bypass scenarios() implementation in the parent class 
        return Model::scenarios(); 
    } 

    /** 
     * Creates data provider instance with search query applied 
     * 
     * @param array $params 
     * 
     * @return ActiveDataProvider 
     */ 
    public function search($params) 
    { 
       $query = Employees::find(); 

        // add conditions that should always apply here 

        $dataProvider = new ActiveDataProvider([ 
            'query' => $query, 
        ]); 

        $this->load($params); 

        if (!$this->validate()) { 
            // uncomment the following line if you do not want to return any 
 records when validation fails 
            // $query->where('0=1'); 
            return $dataProvider; 
        } 

       // grid filtering conditions 
        $query->andFilterWhere([ 
            'id' => $this->id, 
            'contact' => $this->contact, 
        ]); 

        $query->andFilterWhere(['like', 'name', $this->name]) 
            ->andFilterWhere(['like', 'designation', $this->designation]) 
            ->andFilterWhere(['like', 'email', $this->email]); 

        return $dataProvider; 
      } 
  } 

In views, file view.php will have the following code.


<?php 

use yii\helpers\Html; 
use yii\widgets\DetailView; 

/* @var $this yii\web\View */ 
/* @var $model frontend\models\Employees */ 

$this->title = $model->name; 
$this->params['breadcrumbs'][] = ['label' => 'Employees', 'url' => ['index']]; 
$this->params['breadcrumbs'][] = $this->title; 
?> 
<div class="employees-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', 
            'name', 
            'designation', 
            'contact', 
            'email:email', 
        ], 
    ]) ?> 

</div> 

In views, file form.php will have the following code.


<?php 

use yii\helpers\Html; 
use yii\widgets\ActiveForm; 

/* @var $this yii\web\View */ 
/* @var $model frontend\models\Employees */ 
/* @var $form yii\widgets\ActiveForm */ 
?> 

<div class="employees-form"> 

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

    <?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?> 

    <?= $form->field($model, 'designation')->textInput(['maxlength' => true]) ?> 

    <?= $form->field($model, 'contact')->textInput() ?> 

    <?= $form->field($model, 'email')->textInput(['maxlength' => true]) ?> 

    <div class="form-group"> 
        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> 
   </div> 

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

</div> 

In views, file search.php will have the following code.