Shift first Structure item to end


#1

Is there a simple way to move the first item inside a structure field to the last position before looping over it in a template while keeping it an Object? I can convert it to an array but then things get messy inside the iteration.

Thanks.


#2

Yes, like this:

$items= page('somepage')->myStructureField()->toStructure()->offset(1);
$key = $items->count();
$firstItem =  page('somepage')->myStructureField()->toStructure()->first();
$allItems = $items->append($key, $firstItem);

#3

Thanks. Perfect solution, thanks.


#4

Oops, I mean that I needed to move the last item to be the first. Adjusted your code and got close:

$gallery     = $page->gallery()->toStructure();
$last        = $gallery->last();
$gallery     = $gallery->prepend(-1, $last);

This caused the last item to be duplicated, so I tried the following but it’s giving an error:

foreach ($gallery->not($last) as $item) {

Also question about ->prepend(). If the purpose is to add to the beginning, why do you need to define the key? It would always be at the beginning. If I set to 0, it removes the first item.


Move page of collection to last position
#5

It doesn’t. work without a key, but you can still use the $key variable from above:

<?php
$options = $page->gallery()->toStructure();

$key = $options->count();
$lastItem =  $options->last();
$options = $options->limit($key-1);
$newItems = $options->prepend($key, $lastItem);
foreach($newItems as $item) {
  echo $item->title();
}

#6

Thanks. What about removing the last item to prevent duplication from above?


#7

What do you mean by “removing”?


#8

After prepending the last item to first, the original still remains in the last position. I tried ->not($last) but that doesn’t work.


#9

I don’t understand, with the above example, you always have 4 items, nothing duplicated. I limit the original collection to anything but the last item. Then I prepend the last. item.


#10

Apologies, I overlooked your addition of limit().


#11

Similar question, but with pages collection: Move page of collection to last position