Reputation: 466
I want to implement a checkBoxList in my Seachmodel but didn't find a good solution. How can i do this? In My Model i have an Array for the Values:
Model:
const ART_BLACK = 10;
const ART_GREEN = 20;
const ART_ORANGE = 30;
public static function colorText() {
return [
self::ART_BLACK => 'Black',
self::ART_GREEN => 'Green',
self::ART_ORANGE => 'Orange',
];
}
Serach view (_search)
<?= $form->field($model, 'color[]')->checkboxList(Color::colorText()); ?>
After executing the search, all Elements are no longer selected. I can also put the array with the values in the SearchModel but still don't know what's best to save them to display again after the search.
Upvotes: 1
Views: 2808
Reputation: 532
I think you just have to set the search model with separated available options and the selected option
class ColorSearchForm extends Model
{
const ART_BLACK = 10;
const ART_GREEN = 20;
const ART_ORANGE = 30;
public $available_colors = [
self::ART_BLACK => 'Black',
self::ART_GREEN => 'Green',
self::ART_ORANGE => 'Orange',
];
public $selected_colors = [];
/**
* @inheritdoc
*/
public function rules()
{
return [
['selected_colors', 'safe'],
];
}
}
in your controller you just do the standard
public function actionSearch()
{
$model = new ColorSearchForm();
if ($model->load(Yii::$app->request->post())){
// echo '<pre>';print_r($model); exit(); //uncomment to debug
// do something to search
}
return $this->render('index', [
'model' => $model,
]);
}
to display the checkbox in your view:
<div class="goods-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'selected_colors')->checkboxList($model->available_colors) ?>
<div class="form-group">
<?= Html::submitButton('Update', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
Upvotes: 2
Reputation: 4160
create a value array as
$array = [10,20,30];
$searchModel->color = $array;
in _search.php
<?= $form->field($model, 'color')->checkboxList(Color::colorText()); ?>
Upvotes: 1