Creating tags programmatically in 5.6

Permalink
I am writing a tool that imports content from another C5 install (through an XML file).

Everything is working great - importing content, page attributes, images - except for tags. There doesn't appear to be an accepted way to create tags programmatically! Here is an approach:http://www.concrete5.org/community/forums/customizing_c5/cannot-add... but it doesn't work for me: the save() call fails.

Is there a way to create tags programmatically?

pekka
 
hutman replied on at Permalink Reply
hutman
Are you trying to add to the "tags" Attribute?
pekka replied on at Permalink Reply
pekka
Yes, that is the ultimate goal. (It's not as easy as adding to the attribute, though. The tags need to be created in the system.)
hutman replied on at Permalink Reply
hutman
Right, so what you are looking to do is check if that tag is currently in the attribute options list, if it is not then add it, once all the tags are in the attribute options list then set the page's tag attribute, is that correct?
pekka replied on at Permalink Reply
pekka
I guess so! :) To be honest I'm not quite sure about the specifics of how to do this in the context of the C5 API, but that sounds very reasonable.
hutman replied on at Permalink Reply
hutman
You should be able to do something like this

$ak = CollectionAttributeKey::getByHandle('tags');
$tagValues = array();
foreach ($importTags as $tag) {
   if (!$tagValueObject = SelectAttributeTypeOption::getByValue($tag, $ak)) {
      $tagValueObject = SelectAttributeTypeOption::add($ak, $tag);
   }
   $tagValues[] = $tagValueObject;
}
$page->setAttribute('tags', $tagValues);


This assumes that you have an array of tags called $importTags which would looks like array('tag1', 'tag2') then it loops over the list to see if that tag is in the AttributeOptions and if it is, gets that object, if not adds it. Once all of the tags have been tested set the page attribute.
ebirt replied on at Permalink Reply
This is a great reply, Hutman. I would love to see how to do this in 5.8.