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)
Well it finally arrived about a week ago, but with a weekend away between now and then I'm only just getting to grips with it.
Well unlike Godot, my StarLite V Linux Laptop/Tablet is finally on its way having left Godalming in the tender care of Royal Mail. It's been a long long wait, but at least StarLabs provided some (unitentional) humour in the final month.
Starting on writing J5 components with xbMusic I discover a much better way of creating tags progrmatically (see previous version here). Most of this could probably be done in J3 but I didn't realise that. Essentially instead of creating a Table object and separately calling the bind() check() and store() functions you can create a Tags model and just call save. I think the reason I didn't do this before was because of wanting to check within the createGetTag() function that the tag and its parent didn't already exist.
Page 1 of 11