0

这里我在 CActiveForm 中使用 fileField 但在模型中验证规则不适用于该字段这是我的代码

型号代码

public function rules()
{
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
    return array(
        array('image', 'required'),
        //array('imageId, userId, courseId, departmentId, createdOn, lastModifiedOn, lastModifiedBy', 'required'),
        array('image', 'file', 'types' => 'jpg, txt, pdf, gif, png', 'allowEmpty'=>'false'),
        array('courseId, departmentId', 'numerical', 'integerOnly'=>true),
        array('lastModifiedBy', 'length', 'max'=>45),
        array('createdOn, lastModifiedOn', 'safe'),
        // The following rule is used by search().
        // Please remove those attributes that should not be searched.
        array('id, image, imageId, userId, courseId, departmentId, createdOn, lastModifiedOn, lastModifiedBy', 'safe', 'on'=>'search'),
    );
}

查看代码

<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'uploadinfo-form',
'enableAjaxValidation'=>false,
'enableClientValidation' => false,
'htmlOptions' => array('enctype' => 'multipart/form-data'),
)); ?>

<p class="note">Fields with <span class="required">*</span> are required.</p>

<?php //echo $form->errorSummary($model); ?>



<div class="row">
    <?php echo $form->labelEx($model,'image'); ?>
    <?php echo $form->fileField($model,'image'); ?>
    <?php echo $form->error($model,'image'); ?>
</div>

控制器代码

 public function actionCreate()
{

    $model=new Uploadinfo;
    if(isset($_POST['Uploadinfo']))
    {
        $model->attributes=$_POST['Uploadinfo'];
        print_r($_POST['Uploadinfo']);
        $file=CUploadedFile::getInstance($model,'image');
        print_r($file->getName());
        die();
        if($model->save())
        {
            $model->image->saveAs('path/to/localFile');
            // redirect to success page
        }
    }
    $this->render('create', array('model'=>$model));

}

这里所需的文件验证规则不起作用

4

2 回答 2

0

试试这个为你的控制器代码:

 public function actionCreate()
 {      
     $model=new Uploadinfo;
     if(isset($_POST['Uploadinfo']))
     {
        $model->attributes=$_POST['Uploadinfo'];
        $file=CUploadedFile::getInstance($model,'image');
        if($model->validate() && $model->save())
        {
            $model->image->saveAs('path/to/localFile');
        }
    }
    $this->render('create', array('model'=>$model));

}
于 2013-02-21T07:12:17.560 回答
0

你应该设置allow_empty=>true它工作看这个帖子链接

array('image', 'file', 'types' => 'jpg, txt, pdf, gif, png', 'allowEmpty'=>true,'on'=>'update', 'on'=>'insert'),

在你看来

<?php
  $form = $this->beginWidget('CActiveForm', array(
  'id'=>'uploadinfo-form',
  'enableAjaxValidation'=>true,
  'enableClientValidation' => true,
  'htmlOptions' => array('enctype' => 'multipart/form-data'),
)); ?>
于 2013-10-01T19:25:24.997 回答