【问题标题】:Validation is always firing rule message验证总是触发规则消息
【发布时间】:2014-06-09 21:28:28
【问题描述】:

在我将代码复制到之前是 is_valid 规则的验证数组顶部之后,我对图像上传的验证总是触发与要上传的文件的允许大小相关的消息,该规则正在即使文件大小低于限制,即使文件上传成功,也会始终触发。我的is_unique 规则按预期工作,但其余的似乎总是被触发,即使文件遵守规则。是什么触发了这种行为? 我正在使用 CakePHP 2.4.4。

控制器

public function admin_upload_image(){
        $this->set('title_for_layout', 'Inserir Fotografias');
        if(!$this->Session->check('User')) {
            $this->Session->setFlash('Está a aceder a uma zona restrita. Por favor faça Login.');
            $this->redirect(array(
                            'controller' => 'users',
                            'action' => 'login'));
        }

        $this->layout = 'admin_index';
        if($this->request->is('post') || $this->request->is('put')) {
          /*  $file = $this->request->data['gallery_images']['path']['name'];*/
       //debug($this->request->data['gallery_images']['path']['name']);
       //die;
        $file = array(
                'GalleryImage' => array(
                'path' => $this->request->data['gallery_images']['path']['name']
                                        )
                );
            move_uploaded_file($this->data['gallery_images']['path']['tmp_name'], $_SERVER['DOCUMENT_ROOT'] . '/html/PushUp/app/webroot/img/gallery/' . $this->data['gallery_images']['path']['name']);

            $this->loadModel('GalleryImage');

            $this->GalleryImage->create();
           //debug($file);
           //die;
            if($this->GalleryImage->save($file)){
                $validationErrors = $this->GalleryImage->invalidFields();
                $this->Session->setFlash($validationErrors['path']); // named key of the rule
                $this->Session->setFlash('Fotografia guardada com sucesso.', 'default', array('class'=>'alert alert-success'));
            }
            //else{
                //debug($this->GalleryImage->invalidFields());
                //die;
                //$error = $this->Notification->validationErrors;
                //$this->set('error', $error);

                //$this->Session->setFlash(__($error), 'Flash/warning');
            //}
        }
    } 

型号

<?php
App::uses('AppModel', 'Model');
class GalleryImage extends AppModel{
    public $displayField ='path';
    public $useTable = 'gallery_images';
    //public $actsAs = array('MultipleDisplayFields' => array('fields' => array('path', 'id')));
    var $name = 'GalleryImage';
    var $validate= array(
        'path' => array(

            'size' => array(
                'rule' => array('fileSize','<=','1.5MB'),
                'message' => 'O ficheiro deve ter um tamanho igual ou inferior a 1.5MB.',
                //'last' => true,
                'required'=> true),
            'is_valid' => array(
                'rule' => 'fileSelected',
                'message' => 'Seleccione uma fotografia por favor.',
                //'last' => true,
                'required'=> true),
            'extension' => array(
                'rule' => array('extension', array('gif','jpeg','png','jpg')),
                'message'=> 'A imagem deve estar num formato gif, jpeg, png ou jpg.',
                //'last' => true,
                'required'=> true),
            'is_unique' => array(
                'rule' => 'isUnique',
                'message' => 'Uma fotografia com este nome já existe.',
                'required'=> true
                )
            )
        );


/*public function isUploadedFile($params) {
    $val = array_shift($params);
    if ((isset($val['error']) && $val['error'] == 0) || (!empty( $val['tmp_name']) && $val['tmp_name'] != 'none')) {
        return is_uploaded_file($val['tmp_name']);
    }
    return false;
}*/
public function fileSelected($file) {
if(is_array($file) && array_key_exists('path', $file) && !empty($file['path'])) {
    // Seems like a file was set
    return true;
}

// No file set, doesn't validate!
return false;
}
}
?>

查看

<style>
.alert-warning{
    width:100%;
}
.error-message{


}
.col-lg-4{
    width:100%;
}
</style>

<h2>Apagar Fotografia</h2>
<?php echo $this->Session->flash();?>
<br>
<table border="1" bordercolor="#e2e2e2"  width="720" style="word-wrap: break-word" cellpadding="5px" class="">
<tr>
    <?php
        $i=0;
        foreach( $gallery_images as $gallery_image ):?>

        <?php
            echo "<td style=text-align: justify>";
            //echo $gallery_image['GalleryImage']['path'];
            echo $this->Form->postLink('Apagar', array('controller'=>'Galleries', 'action'=>'admin_del_image', $gallery_image['GalleryImage']['id']/*,'prefix'=>'admin'*/), array('class'=>'foto_del btn btn-danger', 'title'=>'Apagar Fotografia'), __('Tem a certeza que quer apagar esta Fotografia?'));
            echo "</td>";
            echo "<td>";
            //$src3 =$this->webroot. 'img/gallery/' .$gallery_image['GalleryImage']['path'];
            echo $this->Html->image('gallery/' . $gallery_image['GalleryImage']['path'] , array('width' => '200px', 'height' => '133px', 'alt' => $gallery_image['GalleryImage']['path'] )); 
            echo "</td>";
            $i++;
            if($i==4){
                echo "</tr><tr>";
                $i=0;   
            }
        ?>
        <?php endforeach ?>
</tr>

</table>

【问题讨论】:

  • 使用'required'=&gt; true 是危险的。如果我是你,我不会那样做。它要求这些字段在保存时始终存在,即使您只是部分更新。 allowEmpty/required 的区别详见here。
  • @mark 你能回答我吗?你解决了这个问题。
  • 文件大小是数据库字段吗?我遇到了同样的问题(验证文件大小)并决定编写一个文件验证方法,它也处理 is_uploaded_file() 和正确的扩展名。允许的大小和文件类型在我的模型类的变量中: public $validateFile = array( 'size' => 307200, 'type' => array('jpeg', 'jpg'), );
  • @CalamityJane 不,文件大小不需要在数据库字段中,我认为文件大小应该在数据数组中执行 size 字段,自动验证。我还没有解决这个问题,所以我使用 ATM,数据库上的 size 字段来存储文件大小,并在我的模型中验证数据数组,如 'size' =&gt; array('sizeCheck' =&gt; array('rule' =&gt; array('comparison', '&lt;=', 2097152),'message' =&gt; 'The file size must be smaller than 2MB.'))。它使用 Cake comparion 规则,你不需要这样自定义代码。
  • SunT 我猜如果文件大小不是数据库字段,验证数组将无法在这里工作。我建议您在 beforeSave 回调函数中进行验证。确保返回 true 表示成功。

标签: validation cakephp file-upload


【解决方案1】:

您正在传递要保存的 $file 变量 $this->GalleryImage->保存($file)

并且您正在手动设置此变量值

$file = array(
          'GalleryImage' => array(
          'path' => $this->request->data['gallery_images']['path']['name']
      )
);

因此您不会将文件信息传递给您的模型。您必须将 $this->request->data['gallery_images']['path'] 传递给您的保存方法

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-07
    • 1970-01-01
    • 1970-01-01
    • 2011-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-10
    相关资源
    最近更新 更多