3

I have a channel called "offers".

My Offers channel contains a field called "Users".

The Users field is the "users" field type. It allows me to select 1 or more users that the Offer is for.

I want to get JSON output for this data based on the "Users" name.

'users/<username:{handle}>/offers.json' => function($username) {
            return [
                'elementType' => 'Entry',
                'criteria' => ['section' => 'specialOffers', 'relatedTo' => $username],
            'transformer' => function(EntryModel $entry) {
                return [
                    'title' => $entry->title,
                    'category' => $entry->category->label,

                ];
              },
            ];
        },
3

You’re close. But the relatedTo param can’t just be set to some username. It has to either be an element ID or an actual element model (more specifically, a user ID or UserModel in this case).

'users/<username:{handle}>/offers.json' => function($username) {
    // Get the actual user model
    $criteria = craft()->elements->getCriteria('User');
    $criteria->username = $username;
    $user = $criteria->first();

    // If there was no user, return no results
    if (!$user) {
        return [
            'elementType' => 'Entry',
            'criteria' => ['id' => false],
        ];
    }

    return [
        'elementType' => 'Entry',
        'criteria' => [
            'section' => 'specialOffers',
            'relatedTo' => ['targetElement' => $user]
        ],
        // ...
    ];
},
| improve this answer | |
  • Thank you!!!! Thank you so much!!! This was it! I didn't realize the relatedTo param had to be an element ID or an actual element model. – Sandy D. Apr 11 '16 at 14:34
  • Is there any way to get the results of a matrix as well? I have a matrix block inside my Entry. I can query the first result on a matrix block in the entry by doing: $entry->mileage->first()->miles. However, I need to get it based on the User. Any suggestions? – Sandy D. Apr 13 '16 at 15:02

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.