yii2gii

Yii2 creating a custom function in the model using Gii model generator


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.


Solution

  • 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.