Search code examples
phpvalidationactive-formyii1.x

How to prevent clearing file field after validation in Yii1


Now the problem is, I have validation rules for each field when i leave the form with an empty value [say Name field is left empty] purposely, it will give me the validation error which is obvious.

but, the other parts of the filled form are kept with the data but only the upload field, [pro picture field] is set to empty.

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,
    ));
}

Solution

  • Use jQuery Ajax Formdata

    $(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
    });
    });
    

    validate your form and return the response in json format

    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,
        ));
    }