3

I'm working on a custom import plugin which needs to import a load of content to fields including categories and tags. Categories is working fine using a comma separated list of category ids:

        $entry = new EntryModel();
        $entry->authorId  = $eventObject->author;
        $entry->enabled   = true;
        $entry->postDate   = $eventObject->postDate;
        $entry->getContent()->title = $eventObject->title;
        $entry->getContent()->setAttributes(array(
            'slug' => $eventObject->slug,
            'locationText' => $eventObject->locationText,
            'date' => $eventObject->eventDate,
            'overview' => $eventObject->overview,
            'eventWebsite' => $eventObject->eventWebsite,
            'eventCategories' => $eventObject->categories,
            'location' => $eventObject->location,
            'eventTags' => 1453,
        ));

I just can't get tags importing at all, also need to create new tags where a tag doesn't already exist! Testing with the id 1453which is an existing tag id.

1 Answer 1

3

Like other relational fields, Tags fields’ values need to be set to an array of the tags’ IDs.

It’s not possible to create tags during entry creation; you would just need to create it first using TagsService::saveTag().

$tag = new TagModel();
$tag->groupId = 1;
$tag->getContent()->title = 'My Tag';

$success = craft()->tags->saveTag($tag);

if ($success)
{
    $tagData = array($tag->id);
}
else
{
    $tagData = null;
}

// ...

$entry->setContentFromPost(array(
    // ...
    'myTagsField' => $tagData,
));

// ...

(Note that I’m setting the field value using setContentFromPost() instead of directly on the ContentModel. This is the recommended way to set your custom field values, although for relational fields it doesn’t really matter either way.)

3
  • Brandon after they are created how do you save tags within "craft()->entries->saveEntry($entry)"? Not sure I understand how setContentFromPost works if it's not a post call? Commented Jan 30, 2015 at 5:56
  • 1
    @AdamMcCombs setContentFromPost() is probably just not the best name for the function. 99% of the time it is called, the data passed in is plucked from $_POST, but that’s not the case here. Commented Jan 30, 2015 at 14:10
  • Thanks Brandon. I think that's what's adding to my confusion because it sounds like setContentFromPost and ->getContent() function the same. getContent (instead of say setContent()) reads funny to me but I know I'm being picky about semantics. Commented Jan 30, 2015 at 16:01

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.