Yii1验证后如何防止清除文件字段

How to prevent clearing file field after validation in Yii1

现在的问题是,我对每个字段都有验证规则 当我故意留下一个空值的表单时[比如名称字段留空],它会给我一个明显的验证错误。

但是,填写的表格的其他部分都保留了数据,只有上传字段,[专业图片字段]设置为空。

HTML

<?php $form=$this->beginWidget('bootstrap.widgets.TbActiveForm',array(
    'id'=>'recruitment-form',
    'enableAjaxValidation'=>false,
    'type'=>'vertical',
    'htmlOptions' => array('enctype' => 'multipart/form-data'),
)); ?>
    <?php echo $form->textFieldRow($modelGeneral,'email',array('maxlength'=>50)); ?> 
   <br/><br/>

 <?php echo $form->fileFieldRow($modelGeneral,'resume', array( 'allowEmpty'=>true)); ?>

PHP

public function actionCreate() {
    $model = new Recruitment('test');
    $modelGeneral = new RecruitmentGeneral;
    if (isset($_POST['RecruitmentGeneral'])) {
        //print_r($_POST['RecruitmentGeneral']);exit;

        $modelGeneral->attributes = $_POST['RecruitmentGeneral'];
        $modelGeneral->DOB = $_POST['RecruitmentGeneral']['DOB'];
        $modelGeneral->middle_name = $_POST['RecruitmentGeneral']['middle_name'];
        $modelGeneral->role = $_POST['RecruitmentGeneral']['role'];
        $modelGeneral->consultancy = $_POST['RecruitmentGeneral']['consultancy'];
        $modelGeneral->comments = $_POST['RecruitmentGeneral']['comments'];
        $modelGeneral->candidate_choice = $_POST['RecruitmentGeneral']['candidate_choice'];
        $modelGeneral->resume = CUploadedFile::getInstance($modelGeneral, 'resume');
        if ($modelGeneral->validate()) {
            $model->attributes = $modelGeneral->attributes;
            $model->createDate = date('Y-m-d');
            $model->candidate_choice = $modelGeneral->candidate_choice;
            if ($model->save()) {
                // chmod(Yii::getPathOfAlias('webroot').'/uploads/resums/', 0777);
                if ($model->resume && $model->id) {
                    if ($model->resume->saveAs((Yii::getPathOfAlias('webroot') . '/uploads/resums/' . $model->id . "_" . $modelGeneral->resume->name))) {
                        $redirect=Yii::app()->createUrl('experince',['id'=>$model->id]);
                    }
                }
                $redirect=Yii::app()->createUrl('experince',['id'=>$model->id]);
            } else {
                $errors = $model->getErrors();
                foreach ($errors as $attribute => $error) {
                    $modelGeneral->addError($attribute, $error[0]);
                }
            }
        }
    }

    $this->render('create', array(
        'modelGeneral' => $modelGeneral,
        'Position' => Designation::designationLists(),
        'Department' => Department::departmentLists(),
        "ReferredBy" => Employee::allUsers(),
        'consultancy' => ConsultancyDetails::consultancies(),
        'roles' => EmployeeRole:: allRoles(),
        'candidateChoice' => StaticCoreComponent::$candidate_choice,
    ));
}

使用jQueryAjax表单数据

$(document).ready(function() {
$('body').on('submit', 'form#recruitment-form', function (e) {
    e.preventDefault();
    var form = $(this);
    var formData = new FormData($(this)[0]);
    $.ajax({
        url    : form.attr('action'),
        type   : 'post',
        contentType: false,
        processData: false,
        data   : formData,
        dataType:'json',
        success: function (response) 
        {
            $(".help-inline").remove();
            $(".error").removeClass();

            if(response.status){
                $(".help-inline").remove();
                $(".error").removeClass();
                window.location.href = response.redirect;
            }else{
                $.each(response, function (key, data) {
                    $("#"+key).addClass('error');
                    $("#"+key).after('<span class="help-inline error">'+data+'</span>');
                    window.scrollTo(0, 0);
                })
            }
        },
        error  : function () 
        {
            console.log('internal server error');
        }
    });
    return false
});
});

验证您的表单并return json 格式的回复

public function actionCreate() {
    $model = new Recruitment('test');
    $modelGeneral = new RecruitmentGeneral;
    if (isset($_POST['RecruitmentGeneral'])) {
        //print_r($_POST['RecruitmentGeneral']);exit;

        $modelGeneral->attributes = $_POST['RecruitmentGeneral'];
        $modelGeneral->DOB = $_POST['RecruitmentGeneral']['DOB'];
        $modelGeneral->middle_name = $_POST['RecruitmentGeneral']['middle_name'];
        $modelGeneral->role = $_POST['RecruitmentGeneral']['role'];
        $modelGeneral->consultancy = $_POST['RecruitmentGeneral']['consultancy'];
        $modelGeneral->comments = $_POST['RecruitmentGeneral']['comments'];
        $modelGeneral->candidate_choice = $_POST['RecruitmentGeneral']['candidate_choice'];
        $modelGeneral->resume = CUploadedFile::getInstance($modelGeneral, 'resume');
        if ($modelGeneral->validate()) {
            $model->attributes = $modelGeneral->attributes;
            $model->createDate = date('Y-m-d');
            $model->candidate_choice = $modelGeneral->candidate_choice;
            if ($model->save()) {
                // chmod(Yii::getPathOfAlias('webroot').'/uploads/resums/', 0777);
                if ($model->resume && $model->id) {
                    if ($model->resume->saveAs((Yii::getPathOfAlias('webroot') . '/uploads/resums/' . $model->id . "_" . $modelGeneral->resume->name))) {
                        $redirect=Yii::app()->createUrl('core/recruitment/experince/id/'.$model->id);
                        echo json_encode(['status'=>'success','redirect'=>$redirect]);
                        Yii::app()->end();
                    }
                }
                $redirect=Yii::app()->createUrl('core/recruitment/experince/id/'.$model->id);
                echo json_encode(['status'=>'success','redirect'=>$redirect]);
                Yii::app()->end();
            } else {
                $errors = $model->getErrors();
                foreach ($errors as $attribute => $error) {
                    $modelGeneral->addError($attribute, $error[0]);
                }
            }
        }else{
            echo CActiveForm::validate($modelGeneral);
            Yii::app()->end();
        }
    }

    $this->render('create', array(
        'modelGeneral' => $modelGeneral,
        'Position' => Designation::designationLists(),
        'Department' => Department::departmentLists(),
        "ReferredBy" => Employee::allUsers(),
        'consultancy' => ConsultancyDetails::consultancies(),
        'roles' => EmployeeRole:: allRoles(),
        'candidateChoice' => StaticCoreComponent::$candidate_choice,
    ));
}