Callback Functions with each?

  • Hi,


    I have a collection called Events, each item has perch:repeater id="event_dates" which can have multiple dates, that might not be in the desired reverse chronological order.


    events--listing.html needs to show the next upcoming date, I feel like this is a job for a callback function. Loop through each item in the collection, order dates and output the first date in the array, then output the HTML


    I can't figure out how to apply arguments to the $item in the callback...


  • Yes, that's right. Dates for each event are added via a repeater, there could be one date or multiple dates per event.


    I've got this half working


    PHP
    1. perch_collection('Events', [
    2. 'template' => '_events/events--listing.html',
    3. 'sort'=>'postDateTime',
    4. 'sort-order'=>'DESC',
    5. 'each' => function($item) {
    6. $item['list_event_date'] = $item['event_dates'][0];
    7. return $item;
    8. }
    9. ]);


    id="list_event_date" is in events--listing.html and takes it's value from the first array in perch:repeater id="event_dates"


    But, I'm not sure how to change the order of the dates in perch:repeater id="event_dates", ideally it needs to be in reverse chronological order so the next upcoming date is shown, not just the first date in the array.


    An admin user might (accidentally) add the dates like this


    - 25th Feb, 2020

    - 12th Feb, 2020

    - 19th Mar, 2020


    My code at the moment would display, 25th Feb, 2020 (the first date in the array). When I'd need it to show 12th Feb, 2020 as that's the next event.

  • But, I'm not sure how to change the order of the dates in perch:repeater id="event_dates", ideally it needs to be in reverse chronological order so the next upcoming date is shown, not just the first date in the array.


    You perhaps can reorder the array with usort(). Assuming your date field inside the repeater has the ID date:


  • Great stuff! Thanks for your help. Here's the working code incase anyone else needs to do something similar.


    :)