这里我在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));
}
此处所需和文件验证规则无法正常工作
答案 0 :(得分: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));
}
答案 1 :(得分:0)
您应该设置allow_empty=>true
才能观看此帖[{3}}:
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'),
)); ?>