user5538720
user5538720

Reputation: 93

Yii2- common function for some controllers- where write code

I have such tables: book and person. One book can be at one person's hands. I created form for book in gii. In the form I can write the name of a book and select a person, which took the book. In book's controller i write

 return $this->render('create', [
        'model' => $model,
        'persons_dropdown' => getDropdown('app\models\Person', 'name'),
    ]);

"persons_dropdown" is the array like 1=>"John Smith", 2=>"Stan Green". The function getDropdown is:

public function getDropdown($model, $colomn)
    {
        $rows = $model::find()->orderBy('id')->asArray()->all();
        return ArrayHelper::map($rows, 'id', $colomn);
    }

The question is- where i should replace function getDropdown() (this function is universal function for any controller and it would be used in some controllers)? Or may be i can get the necessary array by yii tools, without my function.

Upvotes: 0

Views: 338

Answers (1)

ScaisEdge
ScaisEdge

Reputation: 133400

A good solution is create an helper for this type of function

Essentially you could create a proper class in your model and then refer to the related function/method by declaring (public static)

use common/models/YourHelper;


YourHelper::yourMethod();

Someone create a personal vendor and add this kind of common function in an helper subdir

Upvotes: 1

Related Questions