Jump to content

Get template in InputfieldFile::fileAdded hook


DrQuincy
 Share

Recommended Posts

I am resizing images immediately after upload using this in admin.php:

wire()->addHookAfter('InputfieldFile::fileAdded', function($event) { /* ... */ });

The image field can obviously be used in multiple templates and sometimes I may want them sizing differently and want to avoid creating image variations that won't get used. Is it possible to get the template this field belongs to from $event?

Thanks.

 

Link to comment
Share on other sites

1 hour ago, DrQuincy said:

Is it possible to get the template this field belongs to from $event?

I am not sure you can, directly (but others can confirm this). You can get the name of the field though, and its templates. However, couldn't you just get the page being edited and get its template?

Link to comment
Share on other sites

$wire->addHookBefore('InputfieldFile::fileAdded', function($event) {
	/** @var InputfieldFile $inputfield */
	$inputfield = $event->object;
	$page = $inputfield->hasPage;
	if($page && $page->template == 'your_template') {
		// ...
	}
});

 

  • Like 2
Link to comment
Share on other sites

2 hours ago, DrQuincy said:

and couldn't find a way to get from $event to the template.

I understand how this can be tricky. One way to find out what's available is to go down the rabbit hole. In your case, you are dealing with the class InputfieldFile. So, using the search in the API docs here:

https://processwire.com/api/ref/

to look for 'inputfieldFile' would bring you here (the API docs for the Class):

https://processwire.com/api/ref/inputfield-file/

Going through those docs, there is no method or property directly dealing with templates or pages. However, this is a derived class, so the parent class could help. Looking at this ubiquitous note on this page:

Quote

In addition to those shown below, the InputfieldFile class also inherits all the methods and properties of: Inputfield, WireData and Wire.

We might be able to get something in the parent Class, Inputfield:

https://processwire.com/api/ref/inputfield/

So, we head over there and reading through, we find this under Other:

Quote
hasPage null Page The Page object associated with this Inputfield, or null when not applicable or not known.

? 

 

  • 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

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...