문제

Hi everyone, this might sound silly but I don't understand what's the best approach to address this case:

I have a model POST which is associated with another model named FILE. A Post hasMany Files and a File belongsTo a Post. The thing is I want to valid at the moment of creation that every POST contains at least one FILE.

So far I tried this in the beforeSave method of POST:

    public function beforeSave($options = array()) {
        if (isset($this->data[$this->alias]['File'])) {
            if (count($this->data[$this->alias]['File']) == 0) {
                $this->invalidate('File', "Postmust include at least one file.", false);
                return false;
            }
        }
        return true;
    } 

Unfortunately it's not working. Any help is appreciated. Thanks.

도움이 되었습니까?

해결책

If File was send then exist in amount one or greater, if File was not send then it probably return false in your condition.

I suggest something like that:

public function beforeSave($options = array()) {
    if (empty($this->data[$this->alias]['id'])) {
                if (count($this->data[$this->alias]['File']) == 0) {
                    $this->invalidate('File', "Postmust include at least one file.", false);
                    return false;
                }
            }
        return parent::beforeSave($options);
    }

This will work when you create new record where id was not saved yet. I hope this will help.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top