I'm pulling data from a Global Set using the Element API plugin and am wondering if there's a cleaner way to write the transformer function?

My craft/config/elementapi.php file looks like this:

namespace Craft;

return [
    'endpoints' => [
        'api/settings' => [
            'elementType' => 'GlobalSet',
            'criteria' => ['handle' => 'siteSettings'],
            'first' => true,
            'transformer' => function(GlobalSetModel $siteSettings) {
                return [
                    'defaultTitle' => $siteSettings->getContent()['defaultTitle'],
                    'defaultDescription' => $siteSettings->getContent()['defaultDescription']

Thanks in advance!


There’s no need to go through getContent() to access your field values; you can access them directly from the GlobalSetModel:

'transformer' => function(GlobalSetModel $siteSettings) {
    return [
        'defaultTitle' => $siteSettings->defaultTitle,
        'defaultDescription' => $siteSettings->defaultDescription
| improve this answer | |
  • That's what I was initially expecting, however when I try to access the field value as an attribute of $siteSettings, no values are being returned. Are there any gotchas I may be missing on the setup of the globals? – Coppa Mar 7 '16 at 16:26
  • @Coppa Are defaultTitle and defaultDescription just regular Plain Text fields, or something else? – Brandon Kelly Mar 7 '16 at 17:15
  • Ahh, great call. They're rich text fields (I changed the name of these fields for display on SE). I just tested a plain text field, and that let me access the value as you described. I was able to get the value of the rich text field using getParsedContent(). Thanks for the quick help! – Coppa Mar 7 '16 at 18:36

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.