CakePHP Form Validation only on Entering Data

前端 未结 4 1785
星月不相逢
星月不相逢 2021-01-17 07:21

I am trying to Upload a photo for one of the models and when i am going to the edit mode. It still asks me to upload the photo when the user only wants to edit the text rela

4条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-17 07:31

    uploadError expects an upload

    The code for uploadError expects an upload:

    public static function uploadError($check) {
        if (is_array($check) && isset($check['error'])) {
            $check = $check['error'];
        }
    
        return (int)$check === UPLOAD_ERR_OK;
    }
    

    If there is no file uploaded the error will not contain that value - it'll be UPLOAD_ERR_NO_FILE.

    File uploads are never empty

    Putting 'allowEmpty' => true, in the rule definition won't have any effect as the value, if present, will never be empty - it's always of the form:

    array(
        ...
        'error' => int
    )
    

    As such it's best to remove allowEmpty from all the file-upload validation rules.

    Use beforeValidate

    Instead of dealing with the validation rules, you can instead use beforeValidate to simply remove the file upload data before the validation check is made:

    public function beforeValidate() {
        if (
            isset($this->data[$this->alias]['display_photo']) &&
            $this->data[$this->alias]['display_photo']['error'] === UPLOAD_ERR_NO_FILE
        ) {
            unset($this->data[$this->alias['display_photo']);
        }
        return parent::beforeValidate();
    }
    

    In this way the validation rules for display_photo are skipped entirely if there is no upload to process.

提交回复
热议问题