2

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:

<?php
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!

1 Answer 1

3

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
    ];
},
3
  • 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
    Commented Mar 7, 2016 at 16:26
  • @Coppa Are defaultTitle and defaultDescription just regular Plain Text fields, or something else? Commented Mar 7, 2016 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
    Commented Mar 7, 2016 at 18:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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