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.

  1. <?php   
  2.   
  3. namespace frontend\controllers;   
  4.   
  5. use Yii;   
  6. use frontend\models\Employees;   
  7. use frontend\models\EmployeesSearch;   
  8. use yii\web\Controller;   
  9. use yii\web\NotFoundHttpException;   
  10. use yii\filters\VerbFilter;   
  11.   
  12. /**  
  13.  * EmployeesController implements the CRUD actions for Employees model.  
  14.  */   
  15. class EmployeesController extends Controller   
  16. {   
  17.     /**  
  18.      * @inheritdoc  
  19.      */   
  20.     public function behaviors()   
  21.     {   
  22.         return [   
  23.             'verbs' => [   
  24.                 'class' => VerbFilter::className(),   
  25.  'actions' => [   
  26.                     'delete' => ['POST'],   
  27.                 ],   
  28.             ],   
  29.         ];   
  30.     }   
  31.   
  32.     /**  
  33.      * Lists all Employees models.  
  34.      * @return mixed  
  35.      */   
  36.     public function actionIndex()   
  37.     {   
  38.         $searchModel = new EmployeesSearch();   
  39.         $dataProvider = $searchModel->search(Yii::$app->request->queryParams);   
  40.   
  41.         return $this->render('index', [   
  42.             'searchModel' => $searchModel,   
  43.             'dataProvider' => $dataProvider,   
  44.         ]);   
  45.     }   
  46.   
  47.     /**  
  48.      * Displays a single Employees model.  
  49.      * @param integer $id  
  50.      * @return mixed  
  51.      */   
  52.     public function actionView($id)   
  53.     {   
  54.         return $this->render('view', [   
  55.             'model' => $this->findModel($id),   
  56.         ]);   
  57.     }   
  58.   
  59.     /**  
  60.      * Creates a new Employees model.  
  61.      * If creation is successful, the browser will be redirected to the 'view' page.  
  62.      * @return mixed  
  63.      */   
  64.     public function actionCreate()   
  65.     {   
  66.         $model = new Employees();   
  67.   
  68.         if ($model->load(Yii::$app->request->post()) && $model->save()) {   
  69.             return $this->redirect(['view''id' => $model->id]);   
  70.         } else {   
  71.             return $this->render('create', [   
  72.                 'model' => $model,   
  73.             ]);   
  74.         }   
  75.     }   
  76.               
  77. /**  
  78.      * Updates an existing Employees model.  
  79.      * If update is successful, the browser will be redirected to the 'view' page.  
  80.      * @param integer $id  
  81.      * @return mixed  
  82.      */   
  83.     public function actionUpdate($id)   
  84.     {   
  85.         $model = $this->findModel($id);   
  86.   
  87.         if ($model->load(Yii::$app->request->post()) && $model->save()) {   
  88.             return $this->redirect(['view''id' => $model->id]);   
  89.         } else {   
  90.             return $this->render('update', [   
  91.                 'model' => $model,   
  92.             ]);   
  93.         }   
  94.     }   
  95.   
  96.     /**  
  97.      * Deletes an existing Employees model.  
  98.      * If deletion is successful, the browser will be redirected to the 'index' page.  
  99.      * @param integer $id  
  100.      * @return mixed  
  101.      */   
  102.     public function actionDelete($id)   
  103.     {   
  104.         $this->findModel($id)->delete();   
  105.     return $this->redirect(['index']);   
  106.     }   
  107.   
  108.     /**  
  109.      * Finds the Employees model based on its primary key value.  
  110.      * If the model is not found, a 404 HTTP exception will be thrown.  
  111.      * @param integer $id  
  112.      * @return Employees the loaded model  
  113.      * @throws NotFoundHttpException if the model cannot be found  
  114.      */   
  115.     protected function findModel($id)   
  116.     {   
  117.         if (($model = Employees::findOne($id)) !== null) {   
  118.             return $model;   
  119.         } else {   
  120.             throw new NotFoundHttpException('The requested page does not exist.');   
  121.         }   
  122.     }   
  123. }    

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

  1. <?php   
  2.   
  3. namespace frontend\models;   
  4.   
  5. use Yii;   
  6.   
  7. /**  
  8.  * This is the model class for table "employees".  
  9.  *  
  10.  * @property integer $id  
  11.  * @property string $name  
  12.  * @property string $designation  
  13.  * @property integer $contact  
  14.  * @property string $email  
  15.  */   
  16. class Employees extends \yii\db\ActiveRecord   
  17. {   
  18.     /**  
  19.      * @inheritdoc  
  20.      */   
  21.     public static function tableName()   
  22.     {   
  23.         return 'employees';   
  24.     }   
  25.   
  26.     /**  
  27.      * @inheritdoc  
  28.      */   
  29.     public function rules()   
  30.     {   
  31.         return [   
  32.             [['name''designation''contact''email'], 'required'],   
  33.             [['contact'], 'integer'],   
  34.             [['name'], 'string''max' => 20],   
  35.             [['designation'], 'string''max' => 50],   
  36.             [['email'], 'string''max' => 80],   
  37.         ];   
  38.     }   
  39.   
  40.     /**  
  41.      * @inheritdoc  
  42.      */   
  43.     public function attributeLabels()   
  44.     {   
  45.         return [   
  46.             'id' => 'ID',   
  47.             'name' => 'Name',   
  48.             'designation' => 'Designation',   
  49.             'contact' => 'Contact',   
  50.             'email' => 'Email',   
  51.        ];   
  52.     }   
  53. }   
In models, file EmployeesSearch.php will have the following code.
  1. <?php   
  2.   
  3. namespace frontend\models;   
  4.   
  5. use Yii;   
  6. use yii\base\Model;   
  7. use yii\data\ActiveDataProvider;   
  8. use frontend\models\Employees;   
  9.   
  10. /**  
  11.  * EmployeesSearch represents the model behind the search form about `frontend\models\Employees`.  
  12.  */   
  13. class EmployeesSearch extends Employees   
  14. {   
  15.     /**  
  16.      * @inheritdoc  
  17.      */   
  18.     public function rules()   
  19.     {   
  20.         return [   
  21.             [['id''contact'], 'integer'],   
  22.             [['name''designation''email'], 'safe'],   
  23.         ];   
  24.     }   
  25.   
  26.     /**  
  27.      * @inheritdoc  
  28.      */   
  29.     public function scenarios()   
  30.     {   
  31.         // bypass scenarios() implementation in the parent class   
  32.         return Model::scenarios();   
  33.     }   
  34.   
  35.     /**  
  36.      * Creates data provider instance with search query applied  
  37.      *  
  38.      * @param array $params  
  39.      *  
  40.      * @return ActiveDataProvider  
  41.      */   
  42.     public function search($params)   
  43.     {   
  44.        $query = Employees::find();   
  45.   
  46.         // add conditions that should always apply here   
  47.   
  48.         $dataProvider = new ActiveDataProvider([   
  49.             'query' => $query,   
  50.         ]);   
  51.   
  52.         $this->load($params);   
  53.   
  54.         if (!$this->validate()) {   
  55.             // uncomment the following line if you do not want to return any   
  56.     records when validation fails   
  57.             // $query->where('0=1');   
  58.             return $dataProvider;   
  59.         }   
  60.   
  61.        // grid filtering conditions   
  62.         $query->andFilterWhere([   
  63.             'id' => $this->id,   
  64.             'contact' => $this->contact,   
  65.         ]);   
  66.   
  67.         $query->andFilterWhere(['like''name'$this->name])   
  68.             ->andFilterWhere(['like''designation'$this->designation])   
  69.             ->andFilterWhere(['like''email'$this->email]);   
  70.   
  71.         return $dataProvider;   
  72.       }   
  73.   }   

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

  1. <?php   
  2.   
  3. use yii\helpers\Html;   
  4. use yii\widgets\DetailView;   
  5.   
  6. /* @var $this yii\web\View */   
  7. /* @var $model frontend\models\Employees */   
  8.   
  9. $this->title = $model->name;   
  10. $this->params['breadcrumbs'][] = ['label' => 'Employees''url' => ['index']];   
  11. $this->params['breadcrumbs'][] = $this->title;   
  12. ?>   
  13. <div class="employees-view">   
  14.   
  15.     <h1><?= Html::encode($this->title) ?></h1>   
  16.   
  17.     <p>   
  18.        <?= Html::a('Update', ['update''id' => $model->id], ['class' => 'btn btn-primary']) ?>   
  19.         <?= Html::a('Delete', ['delete''id' => $model->id], [   
  20.             'class' => 'btn btn-danger',   
  21.             'data' => [   
  22.                 'confirm' => 'Are you sure you want to delete this item?',   
  23.                 'method' => 'post',   
  24.             ],   
  25.         ]) ?>   
  26.     </p>   
  27.   
  28.     <?= DetailView::widget([   
  29.         'model' => $model,   
  30.         'attributes' => [   
  31.             'id',   
  32.             'name',   
  33.             'designation',   
  34.             'contact',   
  35.             'email:email',   
  36.         ],   
  37.     ]) ?>   
  38.   
  39. </div>   

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

  1. <?php   
  2.   
  3. use yii\helpers\Html;   
  4. use yii\widgets\ActiveForm;   
  5.   
  6. /* @var $this yii\web\View */   
  7. /* @var $model frontend\models\Employees */   
  8. /* @var $form yii\widgets\ActiveForm */   
  9. ?>   
  10.   
  11. <div class="employees-form">   
  12.   
  13.     <?php $form = ActiveForm::begin(); ?>   
  14.   
  15.     <?= $form->field($model'name')->textInput(['maxlength' => true]) ?>   
  16.   
  17.     <?= $form->field($model'designation')->textInput(['maxlength' => true]) ?>   
  18.   
  19.     <?= $form->field($model'contact')->textInput() ?>   
  20.   
  21.     <?= $form->field($model'email')->textInput(['maxlength' => true]) ?>   
  22.   
  23.     <div class="form-group">   
  24.         <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>   
  25.    </div>   
  26.   
  27.     <?php ActiveForm::end(); ?>   
  28.   
  29. </div>   

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

  1. <?php   
  2.   
  3. use yii\helpers\Html;   
  4. use yii\widgets\ActiveForm;   
  5.   
  6. /* @var $this yii\web\View */   
  7. /* @var $model frontend\models\EmployeesSearch */   
  8. /* @var $form yii\widgets\ActiveForm */   
  9. ?>   
  10.   
  11. <div class="employees-search">   
  12.   
  13.     <?php $form = ActiveForm::begin([   
  14.         'action' => ['index'],   
  15.        'method' => 'get',   
  16.     ]); ?>   
  17.   
  18.     <?= $form->field($model'id') ?>   
  19.   
  20.     <?= $form->field($model'name') ?>   
  21.   
  22.     <?= $form->field($model'designation') ?>   
  23.   
  24.     <?= $form->field($model'contact') ?>   
  25.   
  26.     <?= $form->field($model'email') ?>   
  27.   
  28.     <div class="form-group">   
  29.         <?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>   
  30.        <?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>   
  31.     </div>   
  32.   
  33.     <?php ActiveForm::end(); ?>   
  34.   
  35. </div>   

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

  1. <?php   
  2.   
  3. use yii\helpers\Html;   
  4.   
  5.   
  6. /* @var $this yii\web\View */   
  7. /* @var $model frontend\models\Employees */   
  8.   
  9. $this->title = 'Create Employees';   
  10. $this->params['breadcrumbs'][] = ['label' => 'Employees''url' => ['index']];   
  11. $this->params['breadcrumbs'][] = $this->title;   
  12. ?>   
  13. <div class="employees-create">   
  14.   
  15.     <h1><?= Html::encode($this->title) ?></h1>   
  16.   
  17.     <?= $this->render('_form', [   
  18.         'model' => $model,   
  19.     ]) ?>   
  20.   
  21. </div>   

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

  1. <?php   
  2.   
  3. use yii\helpers\Html;   
  4. use yii\grid\GridView;   
  5.   
  6. /* @var $this yii\web\View */   
  7. /* @var $searchModel frontend\models\EmployeesSearch */   
  8. /* @var $dataProvider yii\data\ActiveDataProvider */   
  9.   
  10. $this->title = 'Employees';   
  11. $this->params['breadcrumbs'][] = $this->title;   
  12. ?>   
  13. <div class="employees-index">   
  14.   
  15.     <h1><?= Html::encode($this->title) ?></h1>   
  16.     <?php // echo $this->render('_search', ['model' => $searchModel]); ?>   
  17.   
  18.     <p>   
  19.         <?= Html::a('Create Employees', ['create'], ['class' => 'btn btn-success']) ?>   
  20.     </p>   
  21.     <?= GridView::widget([   
  22.         'dataProvider' => $dataProvider,   
  23.         'filterModel' => $searchModel,   
  24.         'columns' => [   
  25.             ['class' => 'yii\grid\SerialColumn'],   
  26.   
  27.             'id',   
  28.             'name',   
  29.             'designation',   
  30.            'contact',   
  31.             'email:email',   
  32.   
  33.             ['class' => 'yii\grid\ActionColumn'],   
  34.         ],   
  35.     ]); ?>   
  36. </div>   

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

  1. <?php   
  2.   
  3. use yii\helpers\Html;   
  4.   
  5. /* @var $this yii\web\View */   
  6. /* @var $model frontend\models\Employees */   
  7.   
  8. $this->title = 'Update Employees: ' . $model->name;   
  9. $this->params['breadcrumbs'][] = ['label' => 'Employees''url' => ['index']];   
  10. $this->params['breadcrumbs'][] = ['label' => $model->name, 'url' => ['view''id' => $model->id]];   
  11. $this->params['breadcrumbs'][] = 'Update';   
  12. ?>   
  13. <div class="employees-update">   
  14.   
  15.     <h1><?= Html::encode($this->title) ?></h1>   
  16.   
  17.     <?= $this->render('_form', [   
  18.         'model' => $model,   
  19.     ]) ?>   
  20.   
  21. </div>