I am updating an entry using the entries service, I want to add a tag value into a tag field type (classifiedTags).

$entry = craft()->entries->getEntryById(120);
$entry->getContent()->classifiedTags = 'tagtest';
$entry->title = 'Updating title to this';
$entry->getContent()->description = 'this is the new description';

It runs and updates everything except the tag field (classifiedTags).

If I change it from a string to array like below:

$entry->getContent()->classifiedTags = array('tagtest');

It gives me this error:

CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (ggmg_craft.craft_relations, CONSTRAINT craft_relations_targetId_fk FOREIGN KEY (targetId) REFERENCES craft_elements (id) ON DELETE CASCADE). The SQL statement executed was: INSERT INTO craft_relations (fieldId, sourceId, sourceLocale, targetId, sortOrder, dateCreated, dateUpdated, uid) VALUES (:row0_col0, :row0_col1, NULL, :row0_col3, :row0_col4, :row0_col5, :row0_col6, :row0_col7). Bound with :row0_col0='43', :row0_col1='31823', :row0_col3='tagtest', :row0_col4=1, :row0_col5='2016-07-14 21:16:04', :row0_col6='2016-07-14 21:16:04', :row0_col7='d2228ed9-cc60-478d-929c-98efd776b63c'

Which leads me to believe I am getting warmer.

Craft CMS v 2.6.2796 PHP v 5.6.13

1 Answer 1


The Tags field classifiedTags needs an array of tag IDs, not slugs/titles. Also, if this is an existing entry and you want to retain tags already added to the field, you'll need to pull the existing tag IDs using $entry->classifiedTags->ids() and merge with those.

$tag = craft()->elements->getCriteria(ElementType::Tag, [
    'groupId' => 1,
    'slug' => 'tagtest',
if ($tag) {
  $existingTags = $entry->classifiedTags->ids();
  $entry->getContent()->setAttribute('classifiedTags', array_merge($existingTags, [$tag->id]));

Note that if the tag doesn't already exist, you'll need to create it using the TagsService:

$tag->groupId = 1;
$tag->getContent()->title = 'tagtest';
$success = craft()->tags->saveTag($tag);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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