2017-02-23 158 views
2

Теперь проблема заключается в том, что у меня есть правила валидации для каждого поля , когда я оставляю форму с пустым значением [например, поле имени пустое] намеренно, это даст мне ошибка проверки, которая очевидна.Как предотвратить поле поля очистки после проверки в Yii1

, но остальные части заполненной формы хранятся на данных, но только поле для загрузки, [pro picture field] установлено на пустое.

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

ответ

1

Использование 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 
}); 
}); 

проверить свою форму и возвращает ответ в формате 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, 
    )); 
} 

 Смежные вопросы

  • Нет связанных вопросов^_^