Yii无法验证文件输入

时间:2015-05-12 10:20:51

标签: php forms validation file-upload yii

我目前正在使用PHP Yii Framework做一个项目。我有一个表单,要求用户上传文件。在注册过程中,用户上传了文件,但是,当用户提交表单时,表单总是在文件输入上被检测为空白,就好像表单上没有附件一样。下面是代码:

模型 - CandidateResume:

return array(           
      array('resume_file','file','types'=>'doc,docx,pdf', 'allowEmpty'=>true, 'safe'=>true, 'on'=>'register'),
); 

模特 - 候选人:

return array(
      array('can_email,name,repeat_can_email, can_password,repeat_can_password','required', 'on'=>'simplereg'),
);

查看:

$form = $this->beginWidget('bootstrap.widgets.TbActiveForm',array(
    'id'=>'candidate-form',
    'enableAjaxValidation'=>true,
    'type'=>'horizontal',
    'htmlOptions' => array(
            'enctype' => 'multipart/form-data',
            'autocomplete'=>'off', //turn off auto complete in FF
    )
)); 

echo $form->textFieldRow($model,'can_email',array('class'=>'span5','maxlength'=>100)); 
echo $form->textFieldRow($model,'repeat_can_email',array('class'=>'span5','maxlength'=>100)); 
echo $form->passwordFieldRow($model,'can_password',array('class'=>'span5','maxlength'=>100)); 
echo $form->passwordFieldRow($model,'repeat_can_password',array('class'=>'span5','maxlength'=>100)); 
echo $form->fileFieldRow($resume,'resume_file', array('id'=>'resume_file'));  

$this->endWidget();

控制员 - 候选人:

public function actionCreate()
{
    $model = new Candidate();
    $model->setScenario('simplereg');
    $resume = new CandidateResume();
    $resume->setScenario('register');   

    // Uncomment the following line if AJAX validation is needed
    //$this->performAjaxValidation($model);

    if(isset($_POST['Candidate'], $_POST['CandidateResume']))
    {
        $_POST['CandidateResume']['resume_file'] = $resume->resume_file;
        $model->attributes = $_POST['Candidate'];
        $resume->attributes = $_POST['CandidateResume'];

        $uploadedFile = CUploadedFile::getInstance($resume,'resume_file');          

        if($resume->validate() && $model->validate()) 
        {
            $model->save();

            if(!empty($uploadedFile))  // check if uploaded file is set or not
            {
                $saved = $uploadedFile->saveAs(Yii::app()->params['RESUME_PATH'].$model->can_id.'_'.$uploadedFile->getName());
                $resume->resume_file = Yii::app()->params['RESUME_DIR'].$model->can_id.'_'.$uploadedFile->getName();
                $resume->resume_send_ip = Yii::app()->request->userHostAddress;
            }
            $resume->save();

        }
    }

    $this->render('create',array('model'=>$model, 'resume'=>$resume));
}

如果我删除了控制器上的验证:

if($resume->validate() && $model->validate()) 

可以保存表单数据,并在文件夹中正确放置附件。但是,我需要对表单进行验证。因此,我无法跳过这一部分。

我错过了什么吗?我已多次检查并研究解决方案。 All提供了类似的解决方案,因此我无法弄清楚事情。谁能帮我?提前谢谢。

1 个答案:

答案 0 :(得分:2)

您没有设置resume_file属性。它来自$_FILES而不是来自$_POST

$resume->attributes = $_POST['CandidateResume'];
$uploadedFile = CUploadedFile::getInstance($resume,'resume_file');   
$resume->resume_file = $uploadedFile; //add this line