Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Usage in Element API endpoint? #71

Open
sonoflee opened this issue Jun 18, 2021 · 1 comment
Open

Usage in Element API endpoint? #71

sonoflee opened this issue Jun 18, 2021 · 1 comment
Labels
question Further information is requested

Comments

@sonoflee
Copy link

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
Copy link
Contributor

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)
                    ];
                },
            ];
        },
    ]
];

@fvaldes33 fvaldes33 added the question Further information is requested label Oct 7, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

2 participants