How To Use Arrayhelper In Models?

I’m trying to create a method in Yii a model which will get a list of Category




use yii\helpers\ArrayHelper;


public function getCategories()

{

    return ArrayHelper::map(Category::find()->all(), 'id', 'name')

}

However, Yii2 returns:-


app\models\Category cannot use yii\helpers\ArrayHelper - it is not a trait

How do I use ArrayHelper in models?

Thanks

Isn’t this just a case of missing ; at the end of return line?

Not really. Turns out you can’t use ArrayHelper in models. Here’s what I did instead.

Create a method at Category model to find all category.

frontend/models/Category.php


public static function getCategories()

{

    return Category::find()->select(['id', 'name'])->all();

}

Next, send the data to the View file.

frontend/controllers/ArticleController.php


public function actionView($id)

{

    return $this->render('view', [

        'model' => $this->findModel($id),

        'data' => Category::getCategories(),

    ]);

}

And lastly, you can use ArrayHelper on the view like this:-

frontend/views/article/view.php


use yii\widgets\DetailView;

<?= Html::activeDropDownList($model, 'id', ArrayHelper::map($data, 'id', 'name')) ?>

I don’t think so there is any restriction. ArrayHelper is just a normal helper class and using it in models should be same as using it anywhere else in your code. Have used this helper across many classes without issues.

I think the problem is, you are using the use statement wrongly.

Move the use statement to before the class begins, and not within the class definition. This should work:




namespace app\models;


// MOVE YOUR USE STATEMENTS HERE

use yii\helpers\ArrayHelper;


class Category extends \yii\db\ActiveRecord {

    // NO USE STATEMENTS HERE

    public function getCategories()

    {

        return ArrayHelper::map(Category::find()->all(), 'id', 'name');

    }

}