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
Step 2 Generate Model
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.
Look at the above snpashot, click on Generate button to generate the code.
You'll see a successfull message as shown above.
Step 2 Generate CRUD
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/
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.
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.
On clicking Update icon, following page containing John's information will appear where you can edit anything. Click on Update button after making changes.
On clicking Delete icon, following box will appear asking you to delete it or not.
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;
-
-
-
-
- class EmployeesController extends Controller
- {
-
-
-
- public function behaviors()
- {
- return [
- 'verbs' => [
- 'class' => VerbFilter::className(),
- 'actions' => [
- 'delete' => ['POST'],
- ],
- ],
- ];
- }
-
-
-
-
-
- public function actionIndex()
- {
- $searchModel = new EmployeesSearch();
- $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
-
- return $this->render('index', [
- 'searchModel' => $searchModel,
- 'dataProvider' => $dataProvider,
- ]);
- }
-
-
-
-
-
-
- public function actionView($id)
- {
- return $this->render('view', [
- 'model' => $this->findModel($id),
- ]);
- }
-
-
-
-
-
-
- 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,
- ]);
- }
- }
-
-
-
-
-
-
-
- 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,
- ]);
- }
- }
-
-
-
-
-
-
-
- public function actionDelete($id)
- {
- $this->findModel($id)->delete();
- return $this->redirect(['index']);
- }
-
-
-
-
-
-
-
-
- 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;
-
-
-
-
-
-
-
-
-
-
- class Employees extends \yii\db\ActiveRecord
- {
-
-
-
- public static function tableName()
- {
- return 'employees';
- }
-
-
-
-
- public function rules()
- {
- return [
- [['name', 'designation', 'contact', 'email'], 'required'],
- [['contact'], 'integer'],
- [['name'], 'string', 'max' => 20],
- [['designation'], 'string', 'max' => 50],
- [['email'], 'string', 'max' => 80],
- ];
- }
-
-
-
-
- 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;
-
-
-
-
- class EmployeesSearch extends Employees
- {
-
-
-
- public function rules()
- {
- return [
- [['id', 'contact'], 'integer'],
- [['name', 'designation', 'email'], 'safe'],
- ];
- }
-
-
-
-
- public function scenarios()
- {
-
- return Model::scenarios();
- }
-
-
-
-
-
-
-
-
- public function search($params)
- {
- $query = Employees::find();
-
-
-
- $dataProvider = new ActiveDataProvider([
- 'query' => $query,
- ]);
-
- $this->load($params);
-
- if (!$this->validate()) {
-
- records when validation fails
-
- return $dataProvider;
- }
-
-
- $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;
-
-
-
-
- $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;
-
-
-
-
- ?>
-
- <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.
- <?php
-
- use yii\helpers\Html;
- use yii\widgets\ActiveForm;
-
-
-
-
- ?>
-
- <div class="employees-search">
-
- <?php $form = ActiveForm::begin([
- 'action' => ['index'],
- 'method' => 'get',
- ]); ?>
-
- <?= $form->field($model, 'id') ?>
-
- <?= $form->field($model, 'name') ?>
-
- <?= $form->field($model, 'designation') ?>
-
- <?= $form->field($model, 'contact') ?>
-
- <?= $form->field($model, 'email') ?>
-
- <div class="form-group">
- <?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
- <?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>
- </div>
-
- <?php ActiveForm::end(); ?>
-
- </div>
In views, file create.php will have the following code.
- <?php
-
- use yii\helpers\Html;
-
-
-
-
-
- $this->title = 'Create Employees';
- $this->params['breadcrumbs'][] = ['label' => 'Employees', 'url' => ['index']];
- $this->params['breadcrumbs'][] = $this->title;
- ?>
- <div class="employees-create">
-
- <h1><?= Html::encode($this->title) ?></h1>
-
- <?= $this->render('_form', [
- 'model' => $model,
- ]) ?>
-
- </div>
In views, file index.php will have the following code.
- <?php
-
- use yii\helpers\Html;
- use yii\grid\GridView;
-
-
-
-
-
- $this->title = 'Employees';
- $this->params['breadcrumbs'][] = $this->title;
- ?>
- <div class="employees-index">
-
- <h1><?= Html::encode($this->title) ?></h1>
- <?php
-
- <p>
- <?= Html::a('Create Employees', ['create'], ['class' => 'btn btn-success']) ?>
- </p>
- <?= GridView::widget([
- 'dataProvider' => $dataProvider,
- 'filterModel' => $searchModel,
- 'columns' => [
- ['class' => 'yii\grid\SerialColumn'],
-
- 'id',
- 'name',
- 'designation',
- 'contact',
- 'email:email',
-
- ['class' => 'yii\grid\ActionColumn'],
- ],
- ]); ?>
- </div>
In views, file update.php will have the following code.
- <?php
-
- use yii\helpers\Html;
-
-
-
-
- $this->title = 'Update Employees: ' . $model->name;
- $this->params['breadcrumbs'][] = ['label' => 'Employees', 'url' => ['index']];
- $this->params['breadcrumbs'][] = ['label' => $model->name, 'url' => ['view', 'id' => $model->id]];
- $this->params['breadcrumbs'][] = 'Update';
- ?>
- <div class="employees-update">
-
- <h1><?= Html::encode($this->title) ?></h1>
-
- <?= $this->render('_form', [
- 'model' => $model,
- ]) ?>
-
- </div>
0 Comments