6

In Twig code you can use craft->entries->relatedTo to do all sorts of neat things.

From plugin code I am not sure how this works?

$c = craft()->elements->getCriteria(ElementType::Entry);
$c->section = 'concepts';
$c->relatedTo(array('targetElement'=>$e, 'field'=>'entry'));
$concepts = $c->find();

This doesn't throw an error - but it doesn't work either.

How can I use the criteria model to retrieve entries that have some relationship?

Cheers!

1 Answer 1

6

You're very close! Try this:

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section = 'concepts';
$criteria->limit   = null;
$criteria->relatedTo = array(
    'targetElement' => $e,
    'field'         => $field
);
$elements = craft()->elements->findElements($criteria);

Keep in mind, in this instance, $field is the field object which can be retrieved with something like the following:

$singleFieldModel = craft()->fields->getFieldById($singleField);

See the documentation (https://craftcms.com/classreference/services/FieldsService) for other ways to get a field object.

3
  • Thanks! Even more valuable than the correction solution was the link to craftcms.com/classreference! No more grep'ing the source code!
    – gromgull
    Sep 3, 2014 at 14:27
  • Totally. P&T released that a few weeks ago and it's been pretty invaluable.
    – Peter Tell
    Sep 3, 2014 at 14:28
  • Don't know if this has changed since you posted it, but now it seems field should get the field handle, and not the field object.
    – KnutSv
    Jul 8, 2017 at 16:09

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.