简体   繁体   中英

Yii2 transfer logic from view to model

I would like to arrange my code a little bit better. I have this in view, generated by giiant:

$form->field($model, 'land_id')->dropDownList(ArrayHelper::map(app\models\Land::find()->orderBy('name')->all(), 'id', 'name'), [
                'prompt' => Yii::t('app', 'Select'),
                'disabled' => (isset($relAttributes) && isset($relAttributes['land_id'])),]);

Somebody has told me here on stackoverflow that it's not really nice. So I would like to transfer this part:

ArrayHelper::map(app\models\Land::find()->orderBy('name')->all(), 'id', 'name'

into model. The same applies to grid filter dropdowns:

'filter' => ArrayHelper::map(\app\models\base\Land::find()->asArray()->all(), 'id', 'name'),

Does it make sense? I think so, I hope so. I've tried to implement it in model Land 2 ways:

public function getAllAsArray() {
    return ArrayHelper::map(app\models\Land::find()->orderBy('name')->all(), 'id', 'name');
}

or

public function getAllAsArray() {
    return ArrayHelper::map($this->find()->orderBy('name')->all(), 'id', 'name');
}

and I wanted to call it from View/Grid (Zip - Land):

'filter' => $model->land->allAsArray,

but I'm getting the following error: Undefined variable: model

then tried this way:

'filter' => function ($model) {$model->getLand()->one()->getAllAsArray();},
'filter' => function ($model) {$model->getLand()->getAllAsArray();},

then I get no error messages, but it's also not working.

and in Form (Zip - Land) the same way:

$form->field($model, 'land_id')->dropDownList($model->land->allAsArray(), [
            'prompt' => Yii::t('app', 'Select'),
            'disabled' => (isset($relAttributes) && isset($relAttributes['land_id'])),]);

but I'm getting the following error: Call to a member function getAllAsArray() on null

Can you please point me to the right direction? I think I don't understand something basically and this disturbes me. Thank you very much in advance!

Land model

public static function getAllAsArray() {
    return ArrayHelper::map(Land::find()->orderBy('name')->all(), 'id', 'name');
}

index

use app\models\Land;

'filter' => Land::getAllAsArray(),

form

use app\models\Land;

$form->field($model, 'land_id')->dropDownList(Land::getAllAsArray(), [
        'prompt' => Yii::t('app', 'Select'),
        'disabled' => (isset($relAttributes) && isset($relAttributes['land_id']))]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM