如果我用YII上传了一个文件,而另一个规则失败了,那么用户必须再次选择该文件。避免这种情况最简单的方法是什么?
例如,我有一个规则,标题必须是最多20个字符。用户输入21个字母。他选择了一个文件来上传。当用户返回到页面时,文件已经不在那里了,他必须再次选择它,并有效地再次上传它。这是非常令人沮丧的,特别是现在用户将被要求上传多达10个文件。
我知道Drupal是这样工作的。如果上传和其他规则失败,当您返回表单时,这些文件将作为屏幕截图显示。如何在YII上获得相同的功能?
如果我能得到这个扩展覆盖的要求,而不要求用户按下开始上传,我将回家自由
xupload封装的原始插件,有一个额外的回调选项可以使用:.done()
.
在xupload wiki中,访问这些附加选项的方式如下:
<?php
$this->widget('xupload.XUpload', array(
// ... other attributes
'options' => array(
//This is the submit callback that will gather
//the additional data corresponding to the current file
'submit' => "js:function (e, data) {
var inputs = data.context.find(':input');
data.formData = inputs.serializeArray();
return true;
}"
),
));
?>
来源你可能只需要将提交部分更改为done
,并让它将上传文件的URL/路径保存到一个临时隐藏字段,并将验证移到该隐藏字段,这样用户就不必再次上传文件了。
我从这个插件移到coco上传器,因为它更容易实现。
可以启用客户端验证和AJAX验证。因此,在发送表单和上传文件之前,将验证您的常规属性。
可以通过session来实现。
在控制器
// Here I have taken Users as model. you should replace it as your need.
$model=new Users;
if(isset($_POST['Users']))
{
$model->attributes=$_POST['Users'];
//save file in session if User has actually selected a file and there weren't any errors.
if(isset($_FILES['Users']) && $_FILES['Users']['error']['image'] == 0){
Yii::app()->session['image'] = $_FILES['Users'];
}
if(isset(Yii::app()->session['image']) && !empty(Yii::app()->session['image'])){
$model->image = Yii::app()->session['image'];
$model->image = CUploadedFile::getInstance($model,'image');
}
if($model->save())
{
if(!empty($model->image)){
$model->image->saveAs(Yii::app()->basePath.'/images/'.time()."_".$model->image->name);
unset(Yii::app()->session['image']);
//File has successfully been uploaded.
}
// redirect to other page.
}
}
else{
// remember to unset the session variable if it's a get request.
unset(Yii::app()->session['image']);
}
在视图文件
中//Your form fields
//This is to show user that he has already selected a file. You could do it in more sofisticated way.
if(isset(Yii::app()->session['image']) && !empty(Yii::app()->session['image'])) {
echo "<label>".Yii::app()->session['image']['name']['image']."</label><br>";
}
//File uplaod field.
//More form Fields.
希望对你有帮助。