6

I am using the ElementAPI to generate a json response of data based on the value (locations) that was chosen from a drop-down.

I think I have all of the pieces I need, i'm struggling with how to put them all together I think.

twig

{% set locations = craft.categories.group('locations') %}
...
{% for location in locations %}
    <option value="{{ location.slug }}">{{ location.title }}</option>
{% endfor %}

elementapi.php

$slug = craft()->request->getRequiredPost('location');  // chicago
$category = craft()->categories->getGroupByHandle('Locations'); // category group
$location = ??

return [
    'endpoints' => [
        'myfile.json' => [
            'elementType' => 'Entry',
            'criteria' => [
                'section' => 'mysection',
                'relatedTo' => ['targetElement' => $location],
            ],
            'transformer' => function (EntryModel $entry) {
                return [
                    'title' => $entry->title
                ];
            },
        ]
    ]
];
4

I think (well, I know) I am confused by where "regular" php is and where the ElementAPI takes over. This is returning me data, but I'm not sure if it's just dumb luck or I've actually got something working...

$slug = craft()->request->getRequiredPost('location');  // chicago

$criteria = craft()->elements->getCriteria(ElementType::Category);
$criteria->group = 'Locations';
$criteria->slug = $slug;

$locations = $category = $criteria->find();

return [
    'endpoints' => [
        'myfile.json' => [
            'elementType' => 'Entry',
            'criteria' => [
                'section' => 'mysection',
                'relatedTo' => ['targetElement' => $locations],
            ],
            'transformer' => function (EntryModel $entry) {
                return [
                    'title' => $entry->title
                ];
            },
        ]
    ]
];

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.