有条件地验证文件上载

时间:2014-06-25 18:50:42

标签: php yii

我有一个数据库表来管理我的文件上传。 该表描述了必须在表单中上载的文件。所以基本上,它包含用于向用户描述他必须上传的文件的字段。 表中的重要字段是:文件的描述,在允许表单提交之前告诉我是否需要文件的必填字段以及限制要上载的相同类型的文件数的最大字段。 我希望在所需的列值为真时触发验证规则。

class Plan extends CActiveRecord{
    public $Letter, $Copy, $Chamber, $License, $Certificate, $Plans;
    public function rules(){
        return array(
            array( 'id_user, id_type, id_rental, id_city, PropiedadT, date', 'required', 'on' => 'final' ),
            array( 'Letter, Copy, License, Certificate, Chamber, Plans', 'fileExist', 'file','types' => 'jpg,JPG,pdf,doc,docx', 'allowEmpty' => false, 'wrongType'=>'Invalid file', 'on' => 'final', 'message' => 'You must attach a file') );
    }

    public function fileExist($attribute, $params){
        if( !empty( $this->{$attribute} ) ){
            $record = file_exists( "/opt/lampp/htdocs" . Yii::app()->baseUrl . "/files/Plan/" . $this->{$attribute} );
            if( !$record ){
                $this->addError( $attribute, 'You must attach a file' . $this->{$attribute} );
            }
        }
        else{
            $this->addError( $attribute, 'You must attach a file' );
        }
    }
}

我只是想知道我在哪里可以提出这个规则以及如何。

enter image description here

基本上,我有一个用户需要填写许可证的表格X'。每个许可都有不同的类型,根据这种类型,用户需要附加不同的文件。用户需要附加的文件存储在文档表中。此表描述了该文件,并根据需要或不需要将其标记。 每个许可证可以有不同数量的文件,甚至根本没有文件。这些文件可能是必需的。 我的问题打算有可能为这种情况创建验证规则。

1 个答案:

答案 0 :(得分:0)

首先在模型类

中声明文件上载字段的规则
public function rules()
{
        return array(
            array('image','required','on'=>'final'),
            array('image', 'file', 'types'=>'jpg, gif, png'),
        );
}

现在在您的控制器操作中,添加以下行

$model=new Item;
if(isset($_POST['Item']))
{
    $model->attributes=$_POST['Item'];
    $model->image=CUploadedFile::getInstance($model,'image');
    if($model->save())
    {
        $model->image->saveAs('path/to/localFile');
        // redirect to success page
    }
}

确保在表单中添加enctype 'htmlOptions' => array('enctype' => 'multipart/form-data')

有关详细信息,请点击链接 http://www.yiiframework.com/wiki/2/how-to-upload-a-file-using-a-model/

相关问题