Domanda

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.

È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top