如何在使用不同模型时在表单Update中实现kartik yii2 FileInput

时间:2015-06-05 15:05:17

标签: file-io yii2

我已经按照此solution使用多个模型在actionCreate期间使用kartik fileinput上传文件。

我的问题是在actionUpdate期间实现相同的目标,我继续收到以下错误:

  

必须指定'name'或'model'和'attribute'属性。

我的表单视图如下:

echo $form->field($document,'document[]')->widget(FileInput::classname(), [
'options' => ['multiple' => true],
'pluginOptions' => [
   // 'previewFileType' => 'any',
   'showPreview' => false,
    'showUpload' => false
    ], ]);

而我的控制器actionUpdate如下

public function actionUpdate($id)
{
    //$document = new EmployeeDocuments();

    $model = $this->findModel($id);
    $document = EmployeeDocuments::find()->indexBy('employee_id')->all();

      $empavatar=$model->avatar;

      $oldavatar=Yii::$app->session['oldavatar'] = $empavatar;

    if ($model->load(Yii::$app->request->post()) ) {
   // print_r($model); exit;
   // $attachments = UploadedFile::getInstances($document, 'document');
           // print_r($attachments); exit;

    if($model->avatar==""){
    $model->avatar=$oldavatar;
    }
      if ($model->save()){
           if(!empty($attachments)){
            foreach($attachments as $attachment):

            $ext = end((explode(".", $attachment)));
            $filename=end((explode(">", $attachment)));
            $filename = ucwords(substr($filename, 0, strpos($filename, '.')));

            // generate a unique file name
             $file2save = Yii::$app->security->generateRandomString().".{$ext}";
             $path=Yii::getAlias('@loc').'/uploads/employees/docs/'; //set directory path to save image

             $attachment->saveAs($path.$model->id."_".$file2save);   //saving img in folder
             $attachment = $model->id."_".$file2save;    //appending id to image name  

             \Yii::$app->db->createCommand()
          ->insert('lcm_hrm_employee_documents', ['document' => $attachment, 'name'=>$filename,'employee_id'=>$model->id])
              ->execute(); //manually update image name to db /* */

            endforeach;
            }


        return $this->redirect(['view', 'id' => $model->id]);
        }
        else {
        return $this->render('update', [
            'model' => $model, 'document'=>$document
        ]);
        }
    } else {
        return $this->render('update', [
            'model' => $model, 'document'=>$document
        ]);
    }
}

1 个答案:

答案 0 :(得分:0)

将表单视图更改为

echo $form->field($document,'document[]')->widget(FileInput::classname(), [
'options' => ['multiple' => true],
'attribute' =>'document[]',
'pluginOptions' => [
   // 'previewFileType' => 'any',
   'showPreview' => false,
    'showUpload' => false
    ], ]);