YII CRUD

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

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 3

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 frontendmodelsEmployees is generated.

In Search Model class, file EmployeesSearch with the path frontendcontrollersEmployeesSearch is generated.

In Controller class, file EmployeesController with the path @frontendviewsEmployees 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.

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

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

  1.   
  2. namespace frontendmodels;   
  3.   
  4. use Yii;   
  5.   
  6. /**  
  7.  * This is the model class for table "employees".  
  8.  *  
  9.  * @property integer $id  
  10.  * @property string $name  
  11.  * @property string $designation  
  12.  * @property integer $contact  
  13.  * @property string $email  
  14.  */   
  15. class Employees extends yiidbActiveRecord   
  16. {   
  17.     /**  
  18.      * @inheritdoc  
  19.      */   
  20.     public static function tableName()   
  21.     {   
  22.         return 'employees';   
  23.     }   
  24.   
  25.     /**  
  26.      * @inheritdoc  
  27.      */   
  28.     public function rules()   
  29.     {   
  30.         return [   
  31.             [['name''designation''contact''email'], 'required'],   
  32.             [['contact'], 'integer'],   
  33.             [['name'], 'string''max' => 20],   
  34.             [['designation'], 'string''max' => 50],   
  35.             [['email'], 'string''max' => 80],   
  36.         ];   
  37.     }   
  38.   
  39.     /**  
  40.      * @inheritdoc  
  41.      */   
  42.     public function attributeLabels()   
  43.     {   
  44.         return [   
  45.             'id' => 'ID',   
  46.             'name' => 'Name',   
  47.             'designation' => 'Designation',   
  48.             'contact' => 'Contact',   
  49.             'email' => 'Email',   
  50.        ];   
  51.     }   
  52. }   

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

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

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

  1.   
  2. use yiihelpersHtml;   
  3. use yiiwidgetsDetailView;   
  4.   
  5. /* @var $this yiiwebView */   
  6. /* @var $model frontendmodelsEmployees */   
  7.   
  8. $this->title = $model->name;   
  9. $this->params['breadcrumbs'][] = ['label' => 'Employees''url' => ['index']];   
  10. $this->params['breadcrumbs'][] = $this->title;   
  11. ?>   
  12. class="employees-view">   
  13.   
  14.     

    $this->title) ?>

       
  15.   
  16.     

       

  17.        'Update', ['update''id' => $model->id], ['class' => 'btn btn-primary']) ?>   
  18.         'Delete', ['delete''id' => $model->id], [   
  19.             'class' => 'btn btn-danger',   
  20.             'data' => [   
  21.                 'confirm' => 'Are you sure you want to delete this item?',   
  22.                 'method' => 'post',   
  23.             ],   
  24.         ]) ?>   
  25.     

     

       
  26.   
  27.     
  28.         'model' => $model,   
  29.         'attributes' => [   
  30.             'id',   
  31.             'name',   
  32.             'designation',   
  33.             'contact',   
  34.             'email:email',   
  35.         ],   
  36.     ]) ?>   
  37.   
  38.    

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

  1.   
  2. use yiihelpersHtml;   
  3. use yiiwidgetsActiveForm;   
  4.   
  5. /* @var $this yiiwebView */   
  6. /* @var $model frontendmodelsEmployees */   
  7. /* @var $form yiiwidgetsActiveForm */   
  8. ?>   
  9.   
  10. class="employees-form">   
  11.   
  12.     $form = ActiveForm::begin(); ?>   
  13.   
  14.     $form->field($model'name')->textInput(['maxlength' => true]) ?>   
  15.   
  16.     $form->field($model'designation')->textInput(['maxlength' => true]) ?>   
  17.   
  18.     $form->field($model'contact')->textInput() ?>   
  19.   
  20.     $form->field($model'email')->textInput(['maxlength' => true]) ?>   
  21.   
  22.     
    class="form-group">   
  23.         $model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>   
  24.       
  25.   
  26.     end(); ?>   
  27.   
  28.    

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

  1.   
  2. use yiihelpersHtml;   
  3. use yiiwidgetsActiveForm;   
  4.   
  5. /* @var $this yiiwebView */   
  6. /* @var $model frontendmodelsEmployeesSearch */   
  7. /* @var $form yiiwidgetsActiveForm */   
  8. ?>   
  9.   
  10. class="employees-search">   
  11.   
  12.     $form = ActiveForm::begin([   
  13.         'action' => ['index'],   
  14.        'method' => 'get',   
  15.     ]); ?>   
  16.   
  17.     $form->field($model'id') ?>   
  18.   
  19.     $form->field($model'name') ?>   
  20.   
  21.     $form->field($model'designation') ?>   
  22.   
  23.     $form->field($model'contact') ?>   
  24.   
  25.     $form->field($model'email') ?>   
  26.   
  27.     
    class="form-group">   
  28.         'Search', ['class' => 'btn btn-primary']) ?>   
  29.        'Reset', ['class' => 'btn btn-default']) ?>   
  30.        
  31.   
  32.     end(); ?>   
  33.   
  34.    

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

  1.   
  2. use yiihelpersHtml;   
  3.   
  4.   
  5. /* @var $this yiiwebView */   
  6. /* @var $model frontendmodelsEmployees */   
  7.   
  8. $this->title = 'Create Employees';   
  9. $this->params['breadcrumbs'][] = ['label' => 'Employees''url' => ['index']];   
  10. $this->params['breadcrumbs'][] = $this->title;   
  11. ?>   
  12. class="employees-create">   
  13.   
  14.     

    $this->title) ?>

       
  15.   
  16.     $this->render('_form', [   
  17.         'model' => $model,   
  18.     ]) ?>   
  19.   
  20.    

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

 
  1.   
  2. use yiihelpersHtml;   
  3. use yiigridGridView;   
  4.   
  5. /* @var $this yiiwebView */   
  6. /* @var $searchModel frontendmodelsEmployeesSearch */   
  7. /* @var $dataProvider yiidataActiveDataProvider */   
  8.   
  9. $this->title = 'Employees';   
  10. $this->params['breadcrumbs'][] = $this->title;   
  11. ?>   
  12. class="employees-index">   
  13.   
  14.     

    $this->title) ?>

       
  15.     // echo $this->render('_search', ['model' => $searchModel]); ?>   
  16.   
  17.     

       

  18.         'Create Employees', ['create'], ['class' => 'btn btn-success']) ?>   
  19.     

     

       
  20.     
  21.         'dataProvider' => $dataProvider,   
  22.         'filterModel' => $searchModel,   
  23.         'columns' => [   
  24.             ['class' => 'yiigridSerialColumn'],   
  25.   
  26.             'id',   
  27.             'name',   
  28.             'designation',   
  29.            'contact',   
  30.             'email:email',   
  31.   
  32.             ['class' => 'yiigridActionColumn'],   
  33.         ],   
  34.     ]); ?>   
  35.    

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

 
  1.   
  2. use yiihelpersHtml;   
  3.   
  4. /* @var $this yiiwebView */   
  5. /* @var $model frontendmodelsEmployees */   
  6.   
  7. $this->title = 'Update Employees: ' . $model->name;   
  8. $this->params['breadcrumbs'][] = ['label' => 'Employees''url' => ['index']];   
  9. $this->params['breadcrumbs'][] = ['label' => $model->name, 'url' => ['view''id' => $model->id]];   
  10. $this->params['breadcrumbs'][] = 'Update';   
  11. ?>   
  12. class="employees-update">   
  13.   
  14.     

    $this->title) ?>

       
  15.   
  16.     $this->render('_form', [   
  17.         'model' => $model,   
  18.     ]) ?>   
  19.   
  20.