Yii验证规则不起作用

时间:2012-09-28 16:27:44

标签: yii php

我在数据库中创建了一个没有表的文件上传验证规则,所以我只是使用CFormModel扩展它。

这是我的代码:

控制器

public function actionMaterials($pid)
{
    $projectMaterialFile = new ProjectMaterialFile;
    $this->render('project_materials',array(
        'projectMaterialFile'=>$projectMaterialFile,
    ));
}

查看(项目材料)

<div id="exportMaterialContent">
    <h4 style="text-align:left;">Export Material Document</h4>
    <?php echo CHtml::form($this->createUrl("project/export"),'post',array('enctype'=>'multipart/form-data')); ?>
    <?php echo CHtml::activeHiddenField( $projectMaterialFile,'idProject',array('value'=>$projectModel->idProject) ); ?>
    <?php echo CHtml::activeFileField($projectMaterialFile, 'document'); ?>
    <?php echo CHtml::submitButton("Export"); ?>
    <?php echo CHtml::endForm(); ?>
</div>

控制器 - 导出(在提交视图表单后)

public function actionExport()
{
    $model = new ProjectMaterialFile;
    $model->attributes = $_POST['ProjectMaterialFile'];
    if( $model->validate() ) {
        $model->document = CUploadedFile::getInstance($model,'document');
        $model->document->saveAs(Yii::getPathOfAlias('webroot')."/material_document/".$model->document->name);
        echo "correct";
    } else {
        echo "Invalid!";
    }
}

模型

class ProjectMaterialFile extends CFormModel
{
    public $document;
    public $idProject;

    public function rules()
    {
        return array(
            array('document','file','types'=>'csv'),
            array('document', 'required'),
        );
    }

    public function attributeLabels()
    {
        return array(
            'document' => 'Project Material Document',
            'idProject' => 'Project ID',
        );
    }
}

所以我在这里做的是它总是运行到我的控制器actionExport()的其他地方 即使我尝试echo $model->validate();,它也不会打印任何因为它总是转到else语句的原因。

非常感谢您的帮助,当然还有奖励!

谢谢! :)

1 个答案:

答案 0 :(得分:1)

尝试更改模型中的验证规则,如下所示

public function rules()
{
   return array(
      array('document','file','types'=>'csv'),
      array('document', 'required'),
      array('document', 'length', 'max'=>200),
      array('idProject', 'length', 'max'=>200),
      array('document, idProject', 'safe'),
      );
}

现在更改您的控制器部分,如下所示

$model = new ProjectMaterialFile;
$model->attributes = $_POST['ProjectMaterialFile'];
$model->document = CUploadedFile::getInstance($model,'document');

if( $model->validate() )
{
   $model->document->saveAs(Yii::getPathOfAlias('webroot')
                ."/material_document/".$model->document->name);
    echo "Correct";
}
else
{
    echo "Invalid!";
}

示例链接:http://www.yiiframework.com/wiki/2/how-to-upload-a-file-using-a-model/