user4317517
user4317517

Reputation:

Joomla 3.3 Programmatically adding tag to article

I am trying to add tags to article (Joomla 3.3.1)

function saveTags(JTableInterface $table, $newTags = array(), $replace = true){
  $th = new JHelperTags();
  $data = $th->getRowData($table);
  $ucmContentTable = JTable::getInstance('Corecontent');
  $ucm = new JUcmContent($table, 'com_content.article');
  $ucmData = $data ? $ucm->mapData($data) : $ucm->ucmData;
  $primaryId = $ucm->getPrimaryKey($ucmData['common']['core_type_id'], $ucmData['common']'core_content_item_id']);
  $result = $ucmContentTable->load($primaryId);
  $result = $result && $ucmContentTable->bind($ucmData['common']);
  $result = $result && $ucmContentTable->check();
  $result = $result && $ucmContentTable->store();
  $ucmId = $ucmContentTable->core_content_id;

$result = $result && $th->tagItem($ucmId, $table, $newTags, $replace);
}

$table = JTable::getInstance('Content', 'JTable', array());
$table->bind($dataContent);
$table->check();
$table->store();
saveTags($table, array("tag_one", "tag_two"));

but have a error -- Code:

Duplicate entry '0-281-0' for key 'uc_ItemnameTagid' SQL=INSERT INTO new1_contentitem_tag_map
(`type_alias`,`core_content_id`,`content_item_id`,`tag_id`,`tag_date`,`type_id`) VALUES 
('', 12, 281, '0', CURRENT_TIMESTAMP(), 0),('', 12, 281, '0', CURRENT_TIMESTAMP(), 0)

what is wrong with my code?

Upvotes: 1

Views: 972

Answers (1)

karasiov
karasiov

Reputation: 163

Do not call tagItem directly. Use observer.

$table = JTable::getInstance('Content', 'JTable', array());
$table->bind($data);
$table->check();
$table->store();
//you need observer
$tagsObserver = $table->getObserverOfClass('JTableObserverTags');
$tagsObserver->onBeforeStore(true, false);//arguments does not matter here
$tagsObserver->setNewTags(array("1","2","3"), true); //array of tag IDs

Upvotes: 3

Related Questions