marcuzzz
(Marc)
1
Just started with Yii2 and want to know where you would define the options for a listBox in a form that I created with gii.
So in form_.php
I now do this:
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model app\models\Lotto */
/* @var $form yii\widgets\ActiveForm */
// options for listBox
$items[]="No" ;
$items[]="Yes";
$items[]="MayBe";
$items = array_combine($items, $items);
?>
<div …>
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, ‘choose’)->listBox($items) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
It works. Can I leave it like this or should I put $items in the controller / model ?
and how would I do that?
timmy78
(Timothee Planchais)
2
In my case, I like to define the items in my model class like this :
class MyClass extends ActiveRecord
{
const CHOOSE_YES = 1;
const CHOOSE_NO = 0;
const CHOOSE_MAYBE = 2;
public static function getChooses()
{
return [
self::CHOOSE_YES => Yii::t('app', 'Yes'),
self::CHOOSE_NO => Yii::t('app', 'No'),
self::CHOOSE_MAYBE => Yii:t('app', 'Maybe')
];
}
public function getTextChoose()
{
$items = self::getChooses();
return array_key_exists($this->choose, $items) ? $items[$this->choose] : null;
}
public function rules()
{
return [
...
['choose', 'in', 'range' => array_keys(self::getChooses())]
];
}
}
Like this you can use this code in all views
<?= $form->field($model, 'choose')->listBox(MyClass::getChooses()) ?>
Or in the gridView widget :
...
[
'attribute' => 'choose',
'value' => return function($model, $key, $îndex, $column) {
return $model->getTextChoose();
},
'filter' => MyClass::getChooses()
]
marcuzzz
(Marc)
3
Thx for the example that helps!
I’ll move the options to my model.