在Yii2中,可以使用ListBox
控件来实现保存多个选择项的列表框。下面是一个代码示例:
views/site/index.php
),添加以下代码:field($model, 'selectedItems')->listBox($items, ['multiple' => true, 'selected' => $selectedItems]);
echo Html::submitButton('Submit', ['class' => 'btn btn-primary']);
ActiveForm::end();
?>
controllers/SiteController.php
)中,添加以下代码:public function actionIndex()
{
$model = new YourModel(); // 替换为您的模型类
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
// 处理已选择的项
$selectedItems = $model->selectedItems;
// ...
// 保存到数据库或执行其他操作
// ...
}
return $this->render('index', [
'model' => $model,
]);
}
请注意,您需要将YourModel
替换为您自己的模型类。您还可以根据需要进行其他修改,例如添加更多的选择项或更改提交按钮的文本。