2

Is there an easy way to access global sets from an Element API endpoint, so its content can be included in the JSON response?

4

Since Global Sets are elements just like entries, users, etc., you can create API endpoints that are all about them:

'globals/<handle:\w+>' => function($handle) {
    return [
        'elementType' => 'GlobalSet',
        'criteria' => ['handle' => $handle],
        'first' => true,
        'transformer' => function(\Craft\GlobalSetModel $globalSet) {
            return [
                'foo' => $globalSet->foo,
                'bar' => $globalSet->bar,
            ];
        }
    ];
}

You can also manually query for Global Sets, to include their data in an endpoint that’s tied to another element type:

'my/other/endpoint' => [
    'elementType' => 'Entry',
    // ...
    'transformer' => function(\Craft\EntryModel $globalSet) {
        // ...

        // Fetch a global set
        $criteria = craft()->elements->getCriteria(ElementType::GlobalSet);
        $criteria->handle = 'myHandle';
        $myGlobalSet = $criteria->first();

        // Include the global set content in the response data
        return [
            // ...
            'foo' => $myGlobalSet->foo,
            'bar' => $myGlobalSet->bar,
        ]
    }
]

Craft also provides a couple methods for fetching Global Sets by ID or handle, so if that happens to be exactly what you need, feel free to use those:

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for?Browse other questions tagged or ask your own question.