2

I am able to successfully create new entries with PHP when I am using basic field values that are Rich Text or Plain Text fields, but am unsure how to add Tags to an entry.

So my entry already has a field called 'tags' on it, and I thought that maybe it wanted an array of strings like so:

$entry->setFieldValues([
   'tags' => array('someCoolTag', 'tagasaurus rex')
]);

I admit I do not really understand how tags work behind the scenes, and would like to correct that. Any help is great.

2

Tags are normal Elements like Entries, Categories, Users and so on.. In order to relate a Tag to another element, you need to insert the array of those elements like you are used to with every other field

$existingTag = Tag::find()->title('whatever')->one();

$tag = new Tag();
$tag->groupId = 1; //<-- insert your group id here
$tag->title = "something";
Craft::$app->getElements()->saveElement($tag);

$entry->setFieldValues([
   'tags' => [$tag->id, $existingTag->id]
]);
| improve this answer | |
  • This worked. Its unfortunate that I need to use the id of the tag, and cant just use the handle. Do they use the id because there is a possibility of name collisions across different groups of existing tags? – Dan Zuzevich Jun 22 '18 at 16:22
  • Yes that's the case. The title is not unique so the same title can exists in multiple groups but since one tag field is always linked to a certain group you would be able to match the correct one anyway. The more important reason is to keep things consistent. All relation fields use the ID, why should the tag field use something different? It's much more intuitive and logical (if you are used to Craft and know how things work) – Robin Schambach Jun 22 '18 at 18:49
  • Still working on learning all of the craft backend internals. Getting better, but I still have a lot to learn. Makes sense. – Dan Zuzevich Jun 23 '18 at 13:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.