Annoyingly Joomla 5 is still using the ucm_content table for linking tags to items. This is a pain if you want to manipulate tags programatically as you have to get the ucmid before you can use the add an entry to the contentitem_tag_map table..

Here's a simple solution that uses the batch() command in AdminModel and works ok even if the item doesn't yet have ucm_content core_content_id . The batch function creates one for you.

  /**
   * @name addTagToItem()
   * @desc adds an existing tag to an item
   * @param string $compitem - the component item type
     in dotted lower case eg com_content.article
   * @param int $itemId - the id of the ite the tag is being added to
   * @param int $tagId - the id of the tag being added
   * @return boolean - true on success, false on failure
   */
  public function addTagToItem($compitem, $itemId, $tagId) {
    $arr=explode('.',$compitem);
    $app = Factory::getApplication();
    $factory = $app->bootComponent($arr[0])->getMVCFactory();
    $model = $factory->createModel(ucfirst($arr[1]), 'Administrator');
    $commands = array('tag'=>$tagId);
    $pks = [$itemId];
    $contexts = [$itemId=>$compitem.'.'.$itemId];
    $res = $model->batch($commands, $pks, $contexts );
    return $res;
}

Seems to work ok for me. I think tags are about the only thing left using the ucm system. Hopefully it'll get removed soon.

You have to use your own custom getCreateTag() function to get the tagId if you don't have it or if it is a new tag. Easier than farting around with #new# prepended to the tag title. Or use the very simple function in @Zollie answer above.

You could adapt to handle multiple tags and/or items by passing them in as an array and iterating through them building the $contexts array.

Same code could be used to remove tags if your component has implemented an batch.untag command (which IMHO should be part of core Joomla anyway)

Tags:
Joomla:
Tags:

Comments powered by CComment