3
我正在使用kartik - yii2-widget-select2來允許在窗體中創建時選擇多個選項。如何從Select2 Widget將多個值保存到數據庫Yii2
我想輸入兩行或多行到數據庫,具體取決於在select2小部件中選擇的選項數量。
表單中的select2小部件如下所示。
<?= $form->field($model, 'Assign_task_to')->widget(Select2::classname(),
//$data = ArrayHelper::map(Employee::find()->all(),'Employee_ID','employee_name'),
[
'data' => ArrayHelper::map(Employee::find()->all(),'Employee_ID','employee_name'),
'language' => 'en',
'options' => ['placeholder' => 'Select an employee ...', 'multiple' => true],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
控制器actionCreate如下。
public function actionCreate()
{
// set default values
$empModel = new Tasksemp();
$model = new Tasks();
$model->priotiy_level = 'medium';
$model->start_date = date('Y-m-d'); //to get default date
if ($model->load(Yii::$app->request->post())) {
//Check if field input is empty
$model->file = UploadedFile::getInstance($model, 'upload_documents');
if($model->file)
{
//get instance of uploaded file
$fName = time();
$model->file = UploadedFile::getInstance($model, 'upload_documents');
$model->file->saveAs('uploads/'.$fName.'.'.$model->file->extension);
$model->upload_documents = 'uploads/'.$fName.'.'.$model->file->extension;
}
$model->save();
//to save in task_emp table
$empModel->Task_ID = $model->Task_ID;
$empModel->Employee_ID = $model->Assign_task_to; //<---want to save multiple employee IDs with the same Task ID (multiple rows)
$empModel->save(false);
return $this->redirect(['view', 'id' => $model->Task_ID]);
} else {
return $this->render('create', [
'model' => $model,
'emp' => $empModel,
]);
}
}
如何將兩個或多個值保存到數據庫?如何迭代或如何知道選擇了多少個值,以便我可以使用循環插入?
有人可以幫我或給任何建議嗎?謝謝
嗨Jithin。我嘗試了你說的話,但它不起作用。它對數據庫仍然只有一個值。 – user2211486
你Assign_task_to feild是整數還是不是? – jithin
是的,它是整數。 – user2211486