CakePHP 2.x - Can't delete file in model callback

Hi Cake community!

I’m trying to delete a file when the corresponding database record is being deleted. I tried using both beforeDelete() and afterDelete() callbacks, but they didn’t worked.

First, in beforeDelete() callback, I can’t access $this->data. Actually, I can, but it’s empty. Even using the official documentation’s approach (https://book.cakephp.org/2.0/en/models/callback-methods.html#beforedelete), $this->data is empty and I can’t perform the operation.

So, I tried using beforeDelete(). Using $this->findById($this->id) I can get the database record, but when I do the following code I get errors like Notice (8): Undefined index: Atmodel [APP/Model/File.php, line 14] and Notice (8): Undefined index: File [APP/Model/File.php, line 15] repeatedly in the screen. The code is the following:

public function beforeDelete($cascade = true)
{
    $data = $this->findById($this->id);
    $file = new File(WWW_ROOT . 'files/' . $data['Atmodel']['slug'] . '/' . $data['File']['name']);
    if ($file->delete()) {
        return true;
    }
    return false;
}

Using pr($somevariable);exit; I verified that $data has the record I want, $file have it’s File object. Also, the corresponding file exists in the given path, so that isn’t the problem. It’s mostly something with File Utility, but I can’t say for sure, neither dig more on how to solve this.

I’ve “googled” also, about deleting files with their records and accessing record data in callbacks, but I found nothing too much relevant.

Can someone help me with that?

Thanks