Search code examples
phptagspimcore

How to get the tags assigned to a pimcore object?


The pimcore documentation refers to the public static function getTagsForElement($cType, $cId). What values do $cType and $cId take?

I want to (a) assign tags to objects, (b) get the objects with a specific tag, e.g. myTag, and then (c) iterate through the list as in the news and blog examples in the demo system. My question relates to (b).

More specifically, myTag will be held in one object as myTags/myTag/myTarget and the aim to get a list of the other objects tagged with myTags/myTag.

Thank you.


Solution

  • Get all the tags of the object:

    $tags = \Pimcore\Model\Element\Tag::getTagsForElement("object", 3);
    
    foreach ($tags as $tag) {
        echo $tag->getName() . " (ID=" . $tag->getId() . ")<br>";
    }
    

    $cType refers to an element type (object, document, asset) and $cId refers to an element ID (object id, document id, asset id).

    To get a list of objects that have a certain tag use this:

    $type = "object";
    $tagId = 3;
    $tag = Pimcore\Model\Element\Tag::getById($tagId);
    $tagPath = $tag->getFullIdPath();
    
    $considerChildren = true;
    
    if ($considerChildren) {
        $conditionForTags = "o_id IN (SELECT cId FROM tags_assignment INNER JOIN tags ON tags.id = tags_assignment.tagid WHERE ctype = '$type' AND (id = '$tagId' OR idPath LIKE '$tagPath%' ))";
    } else {
        $conditionForTags = "o_id IN (SELECT cId FROM tags_assignment WHERE ctype = '$type' AND tagid = '$tagId')";
    }
    
    $objectList = new \Pimcore\Model\Object\Test\Listing();
    $objectList->setCondition($conditionForTags);
    
    foreach ($objectList as $item) {
        echo $item->getId() . "<br>";
    }
    

    In above example you have to use the ID of the tag and not the name!

    If you want to use this approach on documents and assets, replace o_id with id.