1

In Craft 3, I've got a service function that I'm passing either an 'entry' or 'category' element into.

I'd like to know how to differentiate between the possible element types; This kinda of works:

public function getElementType($element) {
  if ( isset($element->group) ) {
    return = 'category';
  } else if (isset($element->section)) {
    return = 'entry';        
  }
}

However I can't help but feel this is unreliable and hacky. Is there a better way to check an elements elementType?

2

You can also use the PHP function is_a() in addition to the PHP function get_class().

This is a bit different as it also matches classes which have the class as one of its parents, e.g. an element class that extends craft\elements\User.

Example:

if (is_a($element, 'craft\elements\User')) {
    // Do stuff
}

or

if (is_a($element, craft\elements\User::class)) {
    // Do stuff
}
2

There’s no dedicated method on elements, but you can use get_class().

switch (get_class($element)) {
    case Entry::class:
        // it’s an entry
        break;

    case Category::class:
        // it’s a category
        break;
}
  • Just a simple question, would you mind to explain why you use 2 different functions here? I know the behavior of ::class and get_class I would just like to know why you use get_class(element) == Entry::class instead of element::class == Entry::class – Robin Schambach Mar 9 '18 at 20:36
  • They are both very different, ::class returns the fully qualified class name for a class name and get_class() the fully qualified class name for an instance of a class. – carlcs Mar 12 '18 at 9:20
1

I just discovered getElementTypeById()

This pretty much does the trick:

  public function getElementType($element) {

    $elementType = Craft::$app->getElements()->getElementTypeById($element->id);

    if (strpos($elementType, 'Category') !== false) {
      return 'category';
    } else if (strpos($elementType, 'Entry') !== false) {
      return 'entry';
    }

  }

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.