CakePHP Form Validation only on Entering Data

前端 未结 4 1762
星月不相逢
星月不相逢 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.

    0 讨论(0)
  • 2021-01-17 07:36

    Try this approach, I used this several times. Replace 'Model' with your model name.

    if($this->request->data['Molel']['display_photo']['name']!=''){
        // put your code here for upload image
    else
    {
        unset($this->request->data['Model']['display_photo']); // this will exclude this from validation
    }
    
    0 讨论(0)
  • Use required = false and in your controller unset the array field that is not needed for validation based on the application logic.

    0 讨论(0)
  • 2021-01-17 07:56

    set the parameter

    'on' => 'create'
    

    just for the 'uploadError' rule

    'uploadError' => array(
        'rule' => array('uploadError'),
        'message' => 'Please select a Photo.',
        'on' => 'create',
    ),
    

    This way cake will force the user to upload an image just when the record is created.

    The other validation rules, intead, will always be valid, but only if a file is actually uploaded.

    see the manual

    0 讨论(0)
提交回复
热议问题