We're working on an XML import plugin to migrate content from another CMS.
What's the best way to create a new category (with a name, slug etc.) and assign it to the entry when running
$entryModel = new EntryModel();
?
To create a category, you'd have to use the craft()->categories->saveCategory()
method, and feed it a CategoryModel. Having done that, you can use the ID of your new category to create an array for the entry's category field (in this example its handle is categoryFieldHandle
):
$category = new CategoryModel();
$category->groupId = 2; // Or whatever ID your new category's group has.
$category->getContent()->title = 'My new category title'; // Slug will be automagically created
if(craft()->categories->saveCategory($category)) {
$entryModel = new EntryModel();
$entryModel->title = 'My entry's title';
$entryModel->categoryFieldHandle[] = $category->id;
if(craft()->entries->saveEntry($entryModel)) {
...
}
}
ElementCriteriaModel
for this.
Dec 4, 2016 at 13:21
Adding to Paul Verheul's excellent answer (and to answer question by Floriskoch) — to test for the existence of a category before creating it, you might try something like the following (untested).
// Get category group from known id
$categoryGroup = craft()->categories->getGroupById(2);
// Find categories matching group and title
$criteria = craft()->elements->getCriteria(ElementType::Category);
$criteria->group = $categoryGroup;
$criteria->title = "My Category Title";
$criteria->limit = null;
$categories = craft()->elements->findElements($criteria);
// 1 or more matching categories exist; select first category
if($categories) {
$categoryId = $categories[0]->id; // only want first category if more than one with the same title
// no categories exist; create category
} else {
$category = new CategoryModel();
$category->groupId = 2;
$category->getContent()->title = 'My new category title';
if(craft()->categories->saveCategory($category)) {
$categoryId = $category->id;
}
}
// double check we have a category id
if($categoryId) {
$entryModel = new EntryModel();
$entryModel->title = 'My entry's title';
$entryModel->myCategoryFieldHandle[] = $categoryId;
if(craft()->entries->saveEntry($entryModel)) {
...
}
}