1

When querying multiple model types (entries, Commerce products and Commerce variants) I want to be able to detect the model type of each item as I iterate over the results array.

Ideally to avoid this sort of error:

Craft\EntryModel and its behaviors do not have a method or closure named

There doesn't seem to be a clean way of doing this but I may be wrong!

  • Are you doing this from PHP or from Twig? – Brad Bell Aug 16 '17 at 19:27
  • From Twig, hence the confusion... – amogower Aug 16 '17 at 22:52
0

Twig doesn't have a native "instanceof" check, but it'd be pretty trivial to create a simple plugin that added a Twig Extension where you can add an instanceof test.

public function getTests()
{
    return array(
        'instanceof' =>  new \Twig_Function_Method($this, 'isInstanceof')
    );
}

public function isInstanceof($var, $instance)
{
    return  $var instanceof $instance;
}

Then from your template, you'd do something like:

{% if value is instanceof('Commerce_ProductModel') %}
| improve this answer | |
  • Thanks Brad, I was hoping for a solution in Twig but this will do nicely! – amogower Aug 17 '17 at 21:44

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.