Jump to content

Remove file from InputfieldFile before adding file with same filename via hooks


AndZyk
 Share

Recommended Posts

Hello,

I am not that experienced with hooks and was hoping if somebody could me with this task:

I have a InputfieldFile in wich a single generated file will be added after checking a checkbox in the back-end and saving the page. This happens in the saveReady-hook of a page with a specific template inside a ready.php:

<?php
$this->addHookAfter("Pages::saveReady", function($event) {

	$page = $event->arguments(0);

	if ($page->template->name === "example") {
		if ($page->checkboxField) {
			$page->fileField->add($generatedFile);
		}
	}

});

Now if a new file should be generated and there is already a file in this InputfieldFile, I would like to remove the previous file and replace it with the new one:

<?php
if (count($page->fileField)) {
	$page->fileField->removeAll();
}

That works well so far. My problem is, that I want to add the new file with the same name filename.pdf. But when I remove the previous file and add the new file inside the same saveReady-hook, the previous file still exists until the page is saved and the name of the new file will be added a filename-1.pdf, because ProcessWire makes the filename unique when a file with the same name exists.

My question is: Is there a hook or way to remove the previous file before the new file will be added to keep the same filename?

I tried to unlink the previous file, but then the InputfieldFile doesn't always gets updated correctly and has one empty file and the new file. ?

Regards, Andreas

  • Like 1
Link to comment
Share on other sites

Thank you very much @BitPoet for this idea.

Renaming the old file before adding the new file works great. Now the filename of the new one doesn't get changed. ?

<?php
if (count($page->fileField)) {
	foreach ($page->fileField as $pagefile) {
		$pagefile->rename("old_{$pagefile->basename}");
	}

	$page->fileField->removeAll();
}

I was searching for hooks but never thought of such a simple solution. ?

Edited by AndZyk
Added code
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...