Today, I'm excited to show you how to create our code generator, allowing us to use the power of Yii2's tooling and tailor it to our needs.
The Yii2 code generator is a tool that, as the name suggests, helps us generate code, saving us valuable time by providing a base structure that we can customize to suit our preferences and requirements, eliminating the tedious task of manually modifying each view, as most configurations come pre-set by default.
Create Folders: Start by creating the folders frontend/myTemplates/crud or backend/myTemplates/crud, depending on where you'll be working. You can use different templates for each environment.
Copy Default Template: Navigate to vendor\yiisoft\yii2-gii\src\generators\crud and copy the default folder to the folder you created in your application (frontend or backend)/myTemplates/crud.
By doing this, we establish a base code structure, and from there, we only need to make modifications. It's crucial to create our own template in this manner to avoid modifying the vendor, which is something we should never do. While it may seem tempting to modify the vendor directory at first, it's not a good practice, as you probably know.
Modify the Generator: Make necessary modifications to the generator according to your requirements. In another post, I'll demonstrate how to modify the template to add Kartik's GridView. However, everyone has their own ideas about how their ideal view should look. To modify the generator, I recommend experimenting and understanding that this code's purpose is to generate code, plain and simple. Once you grasp this concept, you'll quickly understand how to adapt it to your needs.
Add Code to Configuration: Add the following code to frontend/config/main-local.php or backend/config/main-local.php:
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
'generators' => [ // Here
'crud' => [ // Generator name
'class' => 'yii\gii\generators\crud\Generator', // Generator class
'templates' => [ // Setting for our templates
'myCrud' => '@app/myTemplates/crud/default', // Template name => Path to template
]
]
],
];
Choose Code Generator: Select the code generator you want to use in Yii2's code generator. You'll find this option under "Code Template," just above "Preview."