Reputation: 280
I am working on Yii2 using Gii to generate models. What I am trying to do is to customize my models such that all of them will have the following function
public static function getFoobarList()
{
$models = Foobar::find()->all();
return ArrayHelper::map($models, 'id', 'foobar');
}
Where Foobar is the name of individual models.
Thank you in advance.
Upvotes: 2
Views: 576
Reputation: 2841
You can create a custom template for your models which gii can use to generate your class.
Something like the following, added to the top of a copy of the file /vendor/yiisoft/yii2-gii/generators/model/default/model.php
and the new file stored in, for example, @app/myTemplates/model/default
/**
* your doc string
*/
public static function get<?php echo $className; ?>List()
{
$models = static::find()->all();
return ArrayHelper::map($models, 'id', static::tableName());
}
will add the method you're looking for to any model created with the new template.
In your config something like
// config/web.php for basic app
// ...
if (YII_ENV_DEV) {
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
'allowedIPs' => ['127.0.0.1', '::1', '192.168.0.*', '192.168.178.20'],
'generators' => [ //here
'model' => [ // generator name
'class' => 'yii\gii\generators\model\Generator', // generator class
'templates' => [ //setting for out templates
'myModel' => '@app/myTemplates/model/default', // template name => path to template
]
]
],
];
}
will allow you to select your custom template when using gii, from the 'Code Template' menu.
Upvotes: 3
Reputation: 2499
Since you want this in all the models, another solution would be to add this function in ActiveRecord Model from which all generated models extend. You just need to change the function a bit to perform the required functionality.
Just add this to your ActiveRecord class:
public static function getModelList()
{
$models = static::find()->all();
return ArrayHelper::map($models, 'id', static::tableName());
}
To use this for any model, example Foobar all you'll need to do is:
Foobar::getModelList();
Upvotes: 3