Jump to content
szabesz

addHookMethod example for Pageimage(s)

Recommended Posts

Hi PW fanatics ;)

In this post I share two of my addHookMethods for those interested. As you surely already know (if not, time to take a look at it) the Wire::addHookMethod() and the Wire::addHookProperty() API methods can be used to "breath some extra OOP" into your projects.

Using addHookMethods and addHookProperty are alternatives to "Using custom page types in ProcessWire".

The methods I want to share: basically the idea here is to get the URL pointing to images uploaded in the admin without writing much code in the template files. With methods like these below, it does not matter what Formatted value is set to the images, because some predefined defaults are used in all circumstances.

#1 Example
template file code:

<?php $img_src = $latest_article->siteFeaturedImage(); ?>
<img src="<?= $img_src ?>" alt="<?= $page->title ?>">

addHookMethod goes into /site/init.php

<?php 
/* Returns URL of the original Pageimage of Article.
 * Image field's value can be either null (default missing image), Pageimage or Pageimages.
 * 
 * @return string 
 */
$wire->addHookMethod('Page::siteFeaturedImage', function($event) {
	$page = $event->object;
	if ($page->template != "article") {
		throw new WireException("Page::siteFeaturedImage() only works on 'Pages of article template', Page ID=$page is not such!");
	}
	$article_featured = $page->getUnformatted('article_featured'); //always a Pageimages array
	if (count($article_featured)) {
		$img_url = $article_featured->first()->url;
	} else {
		$img_url = urls()->templates . "assets/img/missing-article_image.jpg"; //we show this when image is not available
	}
	$event->return = $img_url;
});
?>

#2 Example
template file code:

<?php $img600_src = $page->siteProductImageMaxSize(600, 600, ['rotate' => 180]); ?>
<img src="<?= $img600_src ?>" alt="<?= $page->title ?>">

addHookMethod goes into /site/init.php

<?php 
/* Generates image variations for Product images. Returns URL of Pageimage.
 * Image field's value can be either null (default missing image), Pageimage or Pageimages.
 * 
 * @param int arguments[0] Max allowed width
 * @param int arguments[1] Max allowed height
 * @param array arguments[2] See `Pageimage::size()` method for options
 * @return string 
 */
$wire->addHookMethod('Page::siteProductImageMaxSize', function($event) {
	$page = $event->object;
	if ($page->template != "product") {
		throw new WireException("Page::siteProductImageMaxSize() only works on 'Pages of product template', Page ID=$page is not such!");
	}
	$width = isset($event->arguments[0]) ? $event->arguments[0] : 48; //default width
	$height = isset($event->arguments[1]) ? $event->arguments[1] : 48; //default height
	$options = isset($event->arguments[2]) ? $event->arguments[2] : $options = array(); //default empty options
	$product_image = $page->getUnformatted('product_image'); //always a Pageimages array
	if (count($product_image)) {
		$img_url = $product_image->first()->maxSize($width, $height, $options)->url;
	} else {
		$img_url = urls()->templates . "assets/img/product-missing-image.jpg"; //we show this when image is not available
	}
	$event->return = $img_url;
});
?>

BTW, you can find more examples here:

Have a nice weekend!

Edited by szabesz
code updated, thanks Robin
  • Like 10

Share this post


Link to post
Share on other sites

Nice tutorial, thanks!

You could simplify the methods a little by making sure you always get the Images field as a Pageimages array, e.g.

$wire->addHookMethod('Page::siteFeaturedImage', function($event) {
    $page = $event->object;
    if ($page->template != "article") {
        throw new WireException("Page::siteFeaturedImage() only works on 'Pages of article template', Page ID=$page is not such!");
    }
    $article_featured = $page->getUnformatted('article_featured'); // always a Pageimages array
    if (count($article_featured)) {
        $img_url = $article_featured->first()->url;
    } else {
        $img_url = urls()->templates . "assets/img/missing-article_image.jpg"; //we show this when image is not available
    }
    $event->return = $img_url;
});

 

  • Like 4

Share this post


Link to post
Share on other sites
7 hours ago, Robin S said:

by making sure you always get the Images field as a Pageimages array

Aha, yes! Thank you! I keep forgetting that we have unformatted values too. I updated both methods in my original post.
Cheers,

  • Like 4

Share this post


Link to post
Share on other sites

Thank you! This is very useful because I'm not a php expert. Welcome everyone!

  • Like 3

Share this post


Link to post
Share on other sites

Additional tip related to displaying placeholder images:

Above I just hard coded a placeholder image to be shown which might be all what someone needs. However, there are times when we want to let the editors change that picture or we just want it to show up in the admin too. In that case we can use ProcessWire's "Default value (when empty)" setting:

placeholder-image.thumb.jpg.2d3eb16903b24207a5a719b1403b37a2.jpg

  • Like 1

Share this post


Link to post
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

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By gebeer
      Hello all,
      wasn't sure where to put this, so it goes in General section.
      Ryan shows a hook that we can use to mirror files on demand from live server to development environment to be up to date with the files on the server without having to download complete site/assets/files folder.
      I just implemented this but had problems getting files to load from a site in development that is secured with user/password via htaccess.
      First I tried to use WireHttp setHeader method for basic authentication like this
      function mirrorFilesfromLiveServer(HookEvent $event) { $config = $event->wire('config'); $file = $event->return; if ($event->method == 'url') { // convert url to disk path $file = $config->paths->root . substr($file, strlen($config->urls->root)); } if (!file_exists($file)) { // download file from source if it doesn't exist here $src = 'http://mydomain.com/site/assets/files/'; $url = str_replace($config->paths->files, $src, $file); $http = new WireHttp(); // basic authentication $u = 'myuser'; $pw = 'mypassword'; $http->setHeader('Authorization: Basic', base64_encode("$u:$pw")); $http->download($url, $file); } } But, unfortunately this didn't work.
      So now I am using curl to do the download. My hook function now looks like this
      function mirrorFilesfromLiveServer(HookEvent $event) { $config = $event->wire('config'); $file = $event->return; if ($event->method == 'url') { // convert url to disk path $file = $config->paths->root . substr($file, strlen($config->urls->root)); } if (!file_exists($file)) { // download file from source if it doesn't exist here $src = 'http://mydomain.com/site/assets/files/'; $fp = fopen($file, 'w+'); // init file pointer $url = str_replace($config->paths->files, $src, $file); $u = 'myuser'; $pw = 'mypassword'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_TIMEOUT, 50); // crazy high timeout just in case there are very large files curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_USERPWD, "$u:$pw"); // authentication curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); // authentication curl_setopt($ch, CURLOPT_FILE, $fp); // give curl the file pointer so that it can write to it curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); $data = curl_exec($ch); curl_close($ch); } } Now I can load files and images from the htaccess protected development server 🙂
      If anyone knows how to get this to work with WireHttp, please let me know. Thank you.
    • By Guy Incognito
      I've created a simple sports league fixture generator in a template called 'League'. Teams are added as page references then a fixture list is created as a ProFields table by hooking page save to add new rows to the table.
      The bit I need help with is that I'm trying to check a fixture doesn't already exist before adding it to the table (e.g. if a new team is added to the league). I'm trying to do this with a PW selector to filter the fixtures table and check whether Team A vs Team B already exists in the table. Then on the next line checking no fixture was found by using count().
      However as soon as I add the selector the script no longer adds any rows to the table. If I take it out, it all works fine (albeit with duplicate fixtures each time the page is saved). I've also tested the selector in a page template and it filters as expected. It's late here (UK)... I'm probably doing something stupid! Any ideas?
      <?php //Hook page save to generate league fixture lists $wire->addHookAfter("Pages::saved(template=league)", function ($event) { //Get which page has been saved $page = $event->arguments(0); $noFixturesAdded = 0; //For each team in league cycle through and add home fixtures foreach ($page->teams_in_league as $teamA) { foreach ($page->teams_in_league as $teamB) { //Check if fixture already exists $existingFixtures = $page->fixtures("team_a=$teamA,team_b=$teamB"); //Check team A is not the same as team B as you can't play yourself //Then add row to fixture table if ($teamB != $teamA && $existingFixtures->count() < 1 ) { $fixture = $page->fixtures->makeBlankItem(); $fixture->team_a = $teamA->id; $fixture->team_b = $teamB->id; $page->fixtures->add($fixture); $noFixturesAdded ++; } } } //Save updates to table $page->save('fixtures'); $message = "League saved. $noFixturesAdded new fixtures were added"; $this->message($message); });  
    • By Macaco
      It's a bilingual site. There are two pages: "Artists" and "Events" each with a "Page Reference" field connecting each other.
      - Artists has a field where one can choose events available.
      - Events has a field where you can either choose artists available or create new ones.
      The problems: 
      - When I create an "Artist" page and select events from the list, it doesn't update the collection of participating artists on the "Event" page.
      - When I create an artist from the "Event" page. The field 'artist page > settings > language' is not "Active" for the second language.  When the artist page is created manually,"Active" is on by default.
      I know this all have to do with hooks, but I'm don't fully understand the logics.
    • By VeiJari
      Hello forum! 
      I started to write my first hook for Processwire but I'm pretty confused how you should write these. My idea is to hook after publishing in init.php (called before templates)  for a certain template. 
       
      Here's the code: 

      Trying to reset the checkbox (ajasta) and then saving it so it shows unchecked in the admin page when publishing "article" page. 
      But the code isn't doing anything. Not even dumping anything
      What seems to be the problem? And have you made a similar hook for this usage or am I doing it totally wrong? 😄
      Thanks for the support in advance!
    • By EyeDentify
      Hello Gentlemen and Ladies.

      I have not posted for a while but now i need your help figuring out some things.
      The Documentation has come a long way and i love it.
      Though on the page:
      https://processwire.com/api/ref/pageimages/

      I am trying to figure out if when i want to add an image to an existing image field with multiple images alldready in it and using the method $page->images->add()
      <?PHP /* get the images object array for the Page */ $myPageImg = $page->images; /* define the image to add */ $newImg = 'http://www.somesite.com/image.jpg'; /* Thanks Autofahrn, forgot about the output formating */ $page->of(false); /* create a new Pageimage object with the given URL and add to the Pageimages array */ $myPageImg->add($newImg); /* save the page */ $page->save(); ?> I am pretty sure i missed a few steps in the code above?
      Is that string suppose to be an URL like "http://www.somesite.com/image.jpg" and the method will automaticly download the image and create an Pageimage Object and add it to Pageimages array or does it have to exist on the host first and i supply a file path to that image?

      I guess im confused about that, hope you guys could clarify that for me.

      And if it needs to be allready downloaded to my host before adding the image, what would be the best API methods for that task?
      Just point me in the right direction and i will figure it out.
      Sorry for the bad explaination but i could not figure out a better way of asking.

      Thanks in advance.
      /EyeDentify
×
×
  • Create New...