文件验证不适用于蛋糕php

时间:2012-03-04 20:21:31

标签: php cakephp cakephp-1.3

如果我没有选择文件,则时间验证不起作用,并且不会显示消息“无效文件”。

这是行动网址:

http://localhost/carsdirectory/cars/create_ad

create_ad.ctp(视图)

 <?php echo $this->Form->create('Car', array('type' => 'file', 'action' => 'create_ad')); ?>

      <?php echo $this->Form->file('CarImage.image_path')?>

<?php echo $this->Form->end(array('label' => 'Submit', 'name' => 'Submit', 'div' => array('class' => 'ls-submit')));?>

car_image.php(模型)

 <?php
 class CarImage extends AppModel
 {
 var $name = 'CarImage';

 var $belongsTo = 'Car';

 var $validate = array(

 'image_path' => array(

 'rule' => array('extension', array('jpeg', 'jpg', 'png', 'gif')),

 'allowEmpty' => false,

 'required' => true,

 'message' => 'invaid file'
        ),

  'car_id' => array(
          'rule' => "numeric",
           'allowEmpty' => false,
           'message' => 'Car details could not be saved'
      )


       );
 }
 ?>

car_images(表)

字段 - &gt; 1)id 2)image_path 3)car_id

1 个答案:

答案 0 :(得分:3)

正如我评论并建议根据您的计划看起来正确的是您有这些关联:

车型:

public $hasMany = array(
    'CarImage' => array(
        'className' => 'CarImage',
        'foreignKey' => 'car_id',
        'dependent' => true,
        'conditions' => '',
        'fields' => '',
        'order' => '',
        'limit' => '',
        'offset' => '',
        'exclusive' => '',
        'finderQuery' => '',
        'counterQuery' => ''
    ), 
);

CarImage模型:

public $belongsTo = array(
    'Car' => array(
        'className' => 'Car',
        'foreignKey' => 'car_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    )
);

表单字段,因为您可以上传许多文件(只需使用数字增量创建一个新行):

echo $this->Form->file('CarImage.0.image_path');

要验证和上传文件,在CarImage模型中更容易和更一致(我不确定你是否需要$ validate变量中的car_id,如果不起作用,请尝试从$ validate中删除car_id):

public $validate = array(
    'image_path' => array(
        'uploadFile' => array(
            'rule' => array('uploadFile'),
            'message' => 'Invalid file',
        ),
    ),
);

public function uploadFile($params) {
    if ($params['image_path']['error'] == 0) {
        $file = pathinfo($params['image_path']['name']);

        if (in_array($file['extension'], array('jpeg', 'jpg', 'png', 'gif'))) {
            $tmp_file = new File($params['image_path']['tmp_name']);
            if ($tmp_file->copy('folder_inside_webroot' . DS . $file['basename'])) {
                return true;
            }
        }
    }

    return false;
}

您的控制器需要saveAll而不是save

if ($this->Car->saveAll($this->data)) {
    // success
} else {
    // failure
}

我希望它有所帮助。