Jump to content

How to delete a single file?


GradDev
 Share

Recommended Posts

I have a file field named "resume". I want to delete the file saved in it using the API.

The field is limited to only 1 upload of file and the return type is set to "Automatic" which means it will return a single object if a file is available.

Now there are two options that I have tried- delete() and deleteAll().

$page_to_change = $pages->get("name=xyz");

$page_to_change->resume->deleteAll();

//OR
//$page_to_change->resume->delete($page_to_change->resume);

$page_to_change->of(false);
$page_to_change->save();

Both of these give an error like-

Error: Exception: Method Pagefile::deleteAll does not exist or is not callable in this context(...)

I understand that this error is because these two functions work on a wirearray rather than on a file object.

But how do I delete a single file?

Link to comment
Share on other sites

Your code as well as eelkenet’s should work if you set output formatting to false at the top instead of at the bottom. AFAIK, without output formatting, File fields always return a WireArray, or rather, a Pagefiles array, which inherits from WireArray.

In general the reason you disable output formatting is that you can work with the “raw” data before saving. Changing the formatted data and then only disabling output formatting before the save() should be pointless and/or introduce errors. For example, if you have a field with Markdown formatting and you modify its contents without disabling output formatting, you’re modifying and saving the rendered HTML, destroying your original Markdown markup.

  • Like 1
  • Thanks 1
Link to comment
Share on other sites

@Jan Romero Thanks!

The positioning of output formatting was the issue.

The code just needs to be-

$page_to_change->of(false);

$page_to_change = $pages->get("name=xyz");

$page_to_change->resume->deleteAll();

//OR
//$page_to_change->resume->delete($page_to_change->resume);

$page_to_change->save();

This will make $page_to_change->resume be a Pagefiles array rather than just an object; thus both the deleteAll() and delete($Pagefile) functions work on it now.

  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...