2

I am attempting to build an application where Craft handles all of the API based data (JSON). I am using the Element API. I can't find an example anywhere online that outputs Users.

I am trying to output some basics first before I start outputting the custom Matrix fields etc. Here is my elementapi.json:

<?php
namespace Craft;

return [
    'endpoints' => [
        'players.json' => [
            'elementType' => 'User',
            'criteria' => ['group' => 'player'],
            'transformer' => function(EntryModel $entry){
                return [
                    'username' => $entry->$username,
                    'jsonUrl' => UrlHelper::getUrl("player/{$entry->id}.json")
                ];
            },
        ]
    ]
];

Any help or an example with some custom matrix user fields would be much appreciated! Thanks a bunch!

  • Hi Brad, thanks for editing there, sorry I left the namespace out, that is actually is in my elementapi.php . I am just getting a blank page at the moment when I reference mysite.dev.com/players.json – Graham Winston Apr 18 '16 at 17:46
2

If you set the elementType to User, then the transformer will have a UserModel object passed in like so:

<?php
namespace Craft;

return [
    'endpoints' => [
        'players.json' => [
            'elementType' => 'User',
            'criteria' => ['group' => 'player'],
            'transformer' => function(\Craft\UserModel $user) {
                return [
                    'username' => $user->username,
                    'jsonUrl' => UrlHelper::getUrl("player/{$user->id}.json")
                ];
            },
        ]
    ]
];
| improve this answer | |
  • Thanks for getting back to me Brad: I get this: Property "Craft\UserModel." is not defined. – Graham Winston Apr 18 '16 at 17:47
  • Did you get that error before or after my edit? – Brad Bell Apr 18 '16 at 18:01
  • Hi Brad, no all good, thanks a bunch for the help! It would be really helpful to see a full example with specific user profiles JSON like the entries is layed out :) Thanks again! – Graham Winston Apr 18 '16 at 18:03

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.