Is there a direct relation between code in templates and PHP code inside a controller for example? I need to translate

{% set relatedProducts = craft.entries.section('products').relatedTo({
                   targetElement: testVariant,
                   field: "productVariants.productSizes"
}) %} 

into a controller and im not sure how.

1 Answer 1


A very similar question has been asked before How can I follow relations in ElementCriteriaModels from plugin code. You would want something like this:

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

Where $e is testVariant, and $field is productVariants.productSizes, which can be retrieved using craft()->elements->getElementById(id) and craft()->fields->getFieldById(id) or getFieldByHandle(handle) respectively.

To create a controller see the documentation on Controllers.

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.