unionco / calendarize

Calendar Field Type for CraftCMS
MIT License
18 stars 14 forks source link

Usage in Element API endpoint? #71

Open sonoflee opened 3 years ago

sonoflee commented 3 years ago

I'm trying to work up a json feed of events with Element API, and having trouble figuring out how to get calendar occurrences for each event. Would appreciate guidance if anyone else has had success with this

fvaldes33 commented 2 years ago

Anything you can do in twig you can do with php inside an element transformer.

Not tested but something like this could work. I am using the example snippet from the Element API docs.

<?php

use craft\elements\Entry;
use craft\helpers\UrlHelper;

return [
    'endpoints' => [
        'events.json' => function() {
            return [
                'elementType' => Entry::class,
                'criteria' => ['section' => 'news'],
                'transformer' => function(Entry $entry) {
                    // get the next 10 occurrences
                    $eventDates = $entry->yourCalendarizeHandle->getOccurrences(10);
                    // or get recurring events between dates
                    $eventDates = $entry->yourCalendarizeHandle->getOccurrencesBetween('2021-10-01', '2021-10-30');

                    return [
                        'title' => $entry->title,
                        'url' => $entry->url,
                        'jsonUrl' => UrlHelper::url("news/{$entry->id}.json"),
                        'summary' => $entry->summary,
                        'occurrences' => array_map(function ($occurrence) {
                            return $occurrence->next->format('Y-m-d');
                        }, $eventDates)
                    ];
                },
            ];
        },
    ]
];