2

I have two sections, each with a single entry type:

  • Sites
  • Locations

In the Locations entry type I have a Entries field called Site that you can use to relate a Location to a Site entry.

My questions is: how do I show which locations were related to a Site entry when using the Element API? I'd like to display it as an array when using a sites/.json endpoint.

This is what I've tried, but it breaks the endpoint:

'v1/sites/<entryId:\d+>.json' => function($entryId) {
  return [
    'elementType' => 'Entry',
    'criteria' => ['id' => $entryId],
    'first' => true,
    'transformer' => function(EntryModel $entry) {
      $locations = $entry->getChildren()->type('locations')->find();
      foreach ($locations as $location) {
        $locationsInfo[] = [
          'name' => $location->title
        ];
      }

      return [
        'id' => $entry->id,
        'name' => $entry->title,
        'tagline' => $entry->tagline,
        'about' => $entry->about->getParsedContent(),
        'locations' => $locationsInfo,
        'jsonUrl' => UrlHelper::getUrl("v1/sites/{$entry->id}.json")
      ];
    },
  ];
},
8

You’d do this with a brand new element query using the relatedTo param.

Craft 2:

// This is the PHP equivalent of typing `craft.entries()` in a template:
$criteria = craft()->elements->getCriteria(ElementType::Entry);

// Only fetch Location entries that are related to the Site entry:
$criteria->section = 'locations';
$criteria->relatedTo = ['targetElement' => $entry];

$locations = $criteria->find();

Craft 3:

// This is the PHP equivalent of typing `craft.entries()` in a template:
$query = \craft\elements\Entry::find();

// Only fetch Location entries that are related to the Site entry:
$query->section('locations');
$query->relatedTo(['targetElement' => $entry]);

$locations = $query->all();
  • Looks like this broke in the updated version we're using for Craft 3. Getting a Call to undefined function craft() error when loading up the endpoint. – Roger Erik Tinch Dec 1 '17 at 22:33
  • 2
    @Roger you might want to read the documentation github.com/craftcms/docs/blob/master/en/element-queries.md you'll find many things you need to know for Craft 3 but if you are going to create a more complex site (with custom plugins) you must go through the source code or analyze other plugins in order to use everything properly – Robin Schambach Dec 2 '17 at 14:09

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.