我有条款为我的申请中的公司上传徽标.上传和保存创建配置文件工作正常.但是在更新时,如果我不再上传它,徽标就会变空!
这是我的更新表格
<?php $form = ActiveForm::begin([
'options' => ['enctype'=>'multipart/form-data']
]); ?>
.....
<?= $form->field($model, 'logo')->fileInput() ?>
...
Run Code Online (Sandbox Code Playgroud)
我的控制器动作
if ($model->load($_POST) ) {
$file = \yii\web\UploadedFile::getInstance($model, 'logo');
if($file){
$model->logo=$file; }
if($model->save()){
if($file)
$file->saveAs(\Yii::$app->basePath . '/web/images/'.$file);
}
return $this->redirect(['profile']);
} else {
return $this->renderPartial('update', [
'model' => $model,
]);
}
Run Code Online (Sandbox Code Playgroud)
我的规则:
public function rules()
{
return [
[['logo'], 'image', 'extensions' => 'jpg,png', 'skipOnEmpty' => true],
[['name'], 'required'],
[['name', 'description'], 'string'],
];
}
Run Code Online (Sandbox Code Playgroud)
有任何想法吗????
Den*_*G B 11
skipOnEmpty
这里不适用,因为在更新操作中该$model->logo
属性不为空,它将是一个带有文件名的字符串.$file
仍然是一个只有键的数组,但如果没有再次上传,则不是值.所以检查$file->size
而不是检查!empty($file)
.通过修改控制器代码解决了以下问题!
$model = $this->findModel($id);
$current_image = $model->featured_image;
if ($model->load(Yii::$app->request->post())) {
$image= UploadedFile::getInstance($model, 'featured_image');
if(!empty($image) && $image->size !== 0) {
//print_R($image);die;
$image->saveAs('uploads/' . $image->baseName . '.' .$image->extension);
$model->featured_image = 'uploads/'.$image->baseName.'.'.$image->extension;
}
else
$model->featured_image = $current_image;
$model->save();
return $this->redirect(['update', 'id' => $model->module_id]);
} else {
return $this->render('add', [
'model' => $model,
]);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
14926 次 |
最近记录: |