thomas paulson
thomas paulson

Reputation: 237

Remove file when dataobject is deleted

I have 'Resouce' dataobject as below with attachment as has_one relation. I would like to delete the attachment when 'resource' object is deleted.

But what I get is Fatal error: Call to a member function delete() on a non-object in

<?php 
class Resource extends DataObject
{ 
private static $db = array (
    'Name' => 'Varchar(200)',
    'Description' => 'Text',
    'Category' => "Enum('Data, Drafts, Drawings, Reports, Images, Other')",
    'SortOrder' => 'Int'
);

private static $has_one = array (
    'Attachment' => 'File',
    'ResourcePage' => 'ResourcePage'
);


public function onBeforeDelete()
{
    $myAttachment = $this->Attachment();
    $file = DataObject::get_by_id('File', $myAttachment->ID); //we have to make sure it is a Dataobject object      
    $file->delete();
    $file->destroy();       
    return parent::onBeforeDelete();                    
}

}

Upvotes: 0

Views: 389

Answers (1)

user3477804
user3477804

Reputation:

The problem here is your assumption that DataObject::get_by_id always returns an object is incorrect. You could check that $file is a non-false value first, or just do everything through the has_one getter, using:

public function onBeforeDelete() {
    if ($this->Attachment()->exists()) {
        $this->Attachment()->delete();
    }
}

Upvotes: 5

Related Questions