3

I'm trying to create a category through the api to import a load of datas, but I'm stuck, the category won't be saved, and the saveCategory() method just returns false

$category = new CategoryModel();
$category->setContentFromPost(array(
    'groupId'       =>  $this->category_group_id,
    'title'         =>  $data[0],
    'colorCode'     =>  $data[1],
    'colorPreview'  =>  $data[2]
));
$category->enabled = true;
$res = craft()->categories->saveCategory($category);

Can I get a glimpse of what's happening, or the error ?

Is there anything wrong in this code ? Does anyone have a good example/documentation for this ?

Thanks for your help.

Nicolas

5

You can get any validations errors on the category after you've attempted to save it with CategoryModel::getAllErrors() or \CModel::getErrors().

You're also setting the groupId on the Category's ContentModel, but this property is actually on the Category record itself as it sets the relationship directly.

$category = new CategoryModel();
$category->groupId = $this->category_group_id;

$category->SetContentFromPost(array(
    'title' => $data[0],
    'colorCode' => $data[1],
    'colorPreview' => $data[2],
));

if (craft()->categories->saveCategory($category))
{
    return true;
}
else
{
    // dump the error messages
    Craft::dd($category->getAllErrors());
}
3
  • Hi Mike, thanks for the answer, this worked well to get all the errors. The title was causing the problem ("can't be null"). To fix it, I had to set the "title" property this ways : $category->getContent()->title = $data[0]; Is-it a normal behavior ? Nicolas Mar 9 '15 at 14:33
  • Yes, the title and slug are defined on the ContentModel, so that different values can be stored for different locales. Mar 9 '15 at 15:01
  • What if I had to set different values for different locales of the custom fields ? Mar 9 '15 at 15:23

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.