CakePHP:如果文件不存在,则验证表单上载字段

时间:2014-10-16 13:28:37

标签: php validation cakephp

CakePHP 2.x:我正在努力验证表单中的图片上传字段以添加用户。上传字段不是强制性的。但是,在上传图像时,它会始终将字段验证为false。似乎整个验证部分工作。任何帮助将不胜感激

User.php模型:

public $validate = array(
    'picture' => array(
        'required' => false,
        'allowEmpty' => true,
        'custom' => array(
            'rule' => array('imageExist'),
            'message' => 'There is already a picture with that name on the server'
        )
    ));


// function to check if file already exists
public function imageExist($check) {
    $picturename = $check['picture'];
    $path = WWW_ROOT . 'userimages/';
    $file = $path . $picturename;

    if (file_exists($file)) {
        return false;
    } else {
        return true;
    }
}

add.ctp:

<?php 
echo $this->Form->create('User', array('class' => 'form-horizontal', 'role' => 'form', 'div' => false, 'type' => 'file'));
echo $this->Form->input('username', array('label' => "Username"));
echo $this->Form->input('picture', array('label' => "Avatar", 'type' => 'file'));
echo $this->Form>formDefaultActions();
echo $this->Form->end(); 
?>

UserController.php:

public function add() {
    if ($this->request->is('post')) {
        $this->User->create();
        // set picture and path
        $filedir = WWW_ROOT . 'userimages/';
        $file = $filedir . $this->request->data['User']['picture']['name'];

        // upload avatar picture
        move_uploaded_file(
            $this->request->data['User']['picture']['tmp_name'],
            $file
        );
        $this->request->data['User']['picture'] = $this->request->data['User']['picture']['name'];
        if ($this->User->save($this->request->data)) {
            $this->Session->setFlash(__('The user has been added'), 'success' );
            $this->redirect(array(
                'action' => 'index'
            ));
        } else {
            $this->Session->setFlash(__('The user could not be created. Please, try again'), 'error' );
        }
    }
}

2 个答案:

答案 0 :(得分:1)

您需要在上传前检查您的验证,否则将始终为false。如果您上传文件,当cakephp验证您的文件已存在于文件夹中时。

您可以将您的逻辑移动到:

$this->request->data['User']['picture'] = $this->request->data['User']['picture']['name'];
if ($this->User->save($this->request->data)) {
    move_uploaded_file(
        $this->request->data['User']['picture']['tmp_name'],
        $file
    );
}

或者在保存之前检查:

if ($this->User->validates()) {
    if ($this->User->save($this->request->data)) {
        move_uploaded_file(
            $this->request->data['User']['picture']['tmp_name'],
            $file
        );
    }
}

答案 1 :(得分:-1)

评论此

  $this->request->data['User']['picture'] = $this->request->data['User']['picture']['name'];

并将2个语句转换为model,required和allowEmpty.also在你的控制器中替换:

if ($this->User->save($this->request->data))

if ($this->User->save($this->request->data['User']))

并且pic名称应该保存到db