Access previous image in file collection (manual sorting)


#1

Hi, this is my first post here so please bear with me.

I am trying to use Kirby’s $file->prev() function (see here) to access the previous image in a foreach loop. The problem is that the function seems to ignore the manual sorting parameter and instead sorts by filename. Any idea what I could be missing/doing wrong?

Thanks!

<?php foreach($page->images()->sortBy('sort', 'asc')->offset(1) as $image): ?>
  <p>
  Previous image: <?= $image->prev()->filename(); ?><br>
  This image: <?= $image->filename() ?>
  </p>
<?php endforeach ?>

#2

You need a custom method to achieve that, one that accepts a parameter, it’s the same problem for pages, have a look here: https://github.com/texnixe/kirby-custom-methods/blob/master/page-methods/get-next.php


#3

Thank you. I’ll take a look and report back when I get this working (seems a bit daunting at the moment)…


#4

These should work, if the last index is reached, it starts from the beginning and vice versa; if you don’t want this behaviour, you can change it, so that the functions don’t return anything once they have reached the beginning/end.

file::$methods['getNext'] = function($file, $sort='sort', $direction='asc') {
  $siblings = $file->files()->sortBy($sort, $direction );
  $index  = $siblings->indexOf($file);
  $maxIndex = $siblings->indexOf($siblings->last());
  if($index === false) return false;
  if($index === $maxIndex) return $siblings->nth(0);
  return $siblings->nth($index+1);
};

file::$methods['getPrev'] = function($file, $sort='sort', $direction='asc') {
  $siblings = $file->files()->sortBy($sort, $direction );
  $index  = $siblings->indexOf($file);
  $maxIndex = $siblings->indexOf($siblings->last());
  if($index === false) return false;
  if($index === 0) return $siblings->nth($maxIndex);
  return $siblings->nth($index-1);
};

Usage:

$file = $page->files()->sortBy('sort', 'desc')->first();
$next = $file->getNext('sort', 'desc');

#5

Handed on a silver platter. This works brilliantly, thank you so much! :heart_eyes: