Yii2使用活动表单和搜索模型保存选定的复选框列表项
我想在Seachmodel中实现一个复选框列表,但没有找到一个好的解决方案。我该怎么做?在我的模型中,我有一个值数组: 型号:Yii2使用活动表单和搜索模型保存选定的复选框列表项,yii2,checkboxlist,Yii2,Checkboxlist,我想在Seachmodel中实现一个复选框列表,但没有找到一个好的解决方案。我该怎么做?在我的模型中,我有一个值数组: 型号: const ART_BLACK = 10; const ART_GREEN = 20; const ART_ORANGE = 30; public static function colorText() { return [ self::ART_BLACK => 'Black', self::ART
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视图(搜索)
执行搜索后,将不再选择所有元素。我也可以将带有值的数组放在SearchModel中,但仍然不知道保存它们以在搜索后再次显示的最佳方法 创建一个值数组作为
$array = [10,20,30];
$searchModel->color = $array;
in_search.php
<?= $form->field($model, 'color')->checkboxList(Color::colorText()); ?>
我认为您只需使用单独的可用选项和选定选项设置搜索模型
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'],
];
}
}
在控制器中,您只需执行标准操作
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,
]);
}
公共函数actionSearch()
{
$model=新的ColorSearchForm();
如果($model->load(Yii::$app->request->post()){
//echo“”;print_r($model);exit();//取消注释以进行调试
<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>
//做些搜索
}
返回$this->render('index'[
'model'=>$model,
]);
}
要在视图中显示复选框,请执行以下操作:
谢谢,现在可以用了。我发现我犯了一个错误。在$from->字段中,我使用了“selected_colors[]”这不起作用精选颜色的作品。
<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>