Craft CMS Asked on June 22, 2021
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?
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 craftelementsUser
.
Example:
if (is_a($element, 'craftelementsUser')) {
// Do stuff
}
or
if (is_a($element, craftelementsUser::class)) {
// Do stuff
}
Correct answer by Jay on June 22, 2021
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';
}
}
Answered by Mark Notton on June 22, 2021
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;
}
Answered by carlcs on June 22, 2021
Having arrived here from a Google search while trying to do this in Twig rather than PHP, I thought it might help someone in future to leave an answer, even though it doesn't address your question directly:
{{ item is instance of('craftelementsEntry') ? 'This element is an entry!' }}
{{ item is instance of('craftelementsAsset') ? 'This is an asset!' }}
{{ item is instance of('craftelementsCategory') ? 'This is a category!' }}
{{ item is instance of('craftelementsUser') ? 'This is a user!' }}
I find this especially useful in, for example, internal keyword search results listings templates, where the elements that were found might be of different types and you want to take different actions depending on the types.
Answered by James Smith on June 22, 2021
Example: do nothing if element is not Entry
if (!$event->element instanceof craftelementsEntry) { return; }
Answered by Nikolay Bronskiy on June 22, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP