Yii2 - gii and CRUDing

Enable gii

You can access gii via http://somehost/path/to/frontend/web/?r=gii

However if you are accessing gii from a remote client, you will have to enable that IP address.

The yii2 manual states to add this configuration to frontend/config/main-local.php:

'gii' => [
    'class' => 'yii\gii\Module',
    'allowedIPs' => ['127.0.0.1', '::1', '192.168.0.*', '192.168.178.20'] // adjust this to your needs
],

However, this did not work and I updated vendor/yiisoft/yii2-gii/Module.php to include the remote IP as public $allowedIPs = ['127.0.0.1', '::1', '192.168.1.*'];

Let's setup database before we start using gii.

Enable Debug

While you are enabling gii, enable debug as well by updating vendor/yiisoft/yii2-debug/Module.php similar to updating gii

Access debug via URL: http://somehost/path/to/frontend/web/?r=debug

Database

Create a MySQL database

  • Database
  • User and set permissions for user to access above Database
  • Database Objects (tables)

Setup sample tables

Update database settings in common/config/main-local.php

Work gii / Use the generator

The current release has a bug. Create a directory search under the model directory before using gii.

Browse to http://somehost/path/to/frontend/web/?r=gii

Model Generator

Set the following

Tablename exa_*
Modelname (blank)

Output:

generated models/Departments.php
generated models/Employees.php

CRUD Generator

Set the following

Model Class app\models\Employees
Search Model Class app\models\search\EmployeesSearch
Controller Class app\controllers\EmployeesController

Output:

controllers/EmployeesController.php 	
models/search/EmployeesSearch.php 	
views/employees/_form.php 	
views/employees/_search.php 	
views/employees/create.php 	
views/employees/index.php 	
views/employees/update.php 	
views/employees/view.php

Repeat for Departments

Bug

After generation, in the frontend/controllers directory, for both EmployeesController.php & DepartmentsController.php

change namespace app\controllers;

to namespace frontend\controllers;

Test Generated code


QR Code
QR Code tech:yii2:crud (generated for current page)