Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

We're retiring the forums!

The SilverStripe forums have passed their heyday. They'll stick around, but will be read only. We'd encourage you to get involved in the community via the following channels instead:

Data Model Questions /

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo, swaiba

[solverd] remove file when dataobject is deleted


Go to End


3 Posts   1261 Views

Avatar
thomas.paulson

Community Member, 107 Posts

6 August 2014 at 9:53pm

Edited: 07/08/2014 8:34pm


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();
}

}

Avatar
Kirk

Community Member, 67 Posts

7 August 2014 at 9:48am

Does it mention the what line of code is throwing the error as you are deleting a object which removes the object from the cache and then you are trying to call destroy on a deleted object.

It might be and idea to wrap the delete and destroy in a if statement checking if the object actually exists before trying to delete it.

if ($file && $file->exists()) {
        $file->delete();
        $file->destroy();
}

Avatar
thomas.paulson

Community Member, 107 Posts

7 August 2014 at 8:32pm

Edited: 07/08/2014 8:33pm

Yes Kirk, you are right 'if' condition was missing.

The error was due logical, I should have checked whether file exists, before doing delete method

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

thanks Kirk