Add() function not working

I’m using the add() function to add a hand-picked page to the front of a collection, as a highlighted page, based on this example, but it still won’t work.

$highlight = (string)$site->find('home')->highlight(); //from a select field
$entries = $site->grandChildren()->visible()->without($highlight)->sortBy('date', 'asc');

I get is my collection as usual, with an empty page at the end.

The flip() is there so that the added page ends up first, but it’s not even taking effect, so I guess the problem happens just before, at the add().

Already tried supplying the add() with all possible sorts of things (page object, id, uid, etc).

Can you try this?

$highlight = page(page('home')->highlight());
$entries = $site->grandChildren()->visible()->without($highlight)->sortBy('date', 'desc')->append($highlight);

page() is similar to $site->find()
append is similar to add but it does what you want straight away, it adds in the first position.

1 Like

If you want to prepend the page, you can use $collection->prepend():

$highlight = page(page('home')->highlight());
$key= page('home')->highlight();
$collection->prepend($key, $highlight);

Or maybe

$key= page('home')->highlight()->value();

to get a string.

1 Like

Great! :slight_smile: Thanks @Thiousi and @texnixe!

$collection->prepend() works best for my purpose. I just used prepend(0, $highlight) and avoided the $key value. Hope that’s a correct usage.

I guess the key should be the ID … as in this example and the docs:

BTW: $collection->append() uses the same syntax, so it should be:

$collection->append($key, $highlight);

Edit: And to clarify this:

  • append() adds the page(s) at the end of the collection
  • prepend() adds the page(s) at the beginning of the collection
1 Like

Thanks for the clarification.

So $key is an arbitrary value then. If I want to, it can be different from the ID of the original page, right?

collection does only have add(). but pages inhering from collection has append() as well, right? so using add() on pages will not have the desired effect. append() should be used.

like @lukasbestle corrected me below… above is not right. collection has append and prepend. pages has add.

It’s the other way around. append and prepend are methods in the Collection class, add is specific to Pages collections.

It can, but to ensure compatibility it shouldn’t be. You should always use $p->uid() as key.

1 Like

you are right i will edit post above to avoid confusion.