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've moved the forum!

Please use forum.silverstripe.org for any new questions (announcement).
The forum archive will stick around, but will be read only.

You can also use our Slack channel or StackOverflow to ask for help.
Check out our community overview for more options to contribute.

Data Model Questions /

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

[solverd] remove file when dataobject is deleted


Go to End


3 Posts   2190 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