In a custom plugin, I'm able to easily add a new Category:

$category = new CategoryModel();
$category->groupId = 1;
$category->getContent()->title = $categoryName;

That part works great! But for some reason, I can't figure out how to save a nested category.

I'd imagine it's something like this, but it doesn't seem to be working:

$childCategory = new CategoryModel();
$childCategory->groupId = 1;
$childCategory->level = 2;
$childCategory->parent = $parentCategory->id;
$childCategory->getContent()->title = $childCategoryName;

Unfortunately that code is giving me an error:

Internal Server Error

Trying to get property of non-object

And if I drop the ->id portion of this line:

$childCategory->parent = $parentCategory;

... it will save the category, but it won't be nested.

What am I doing wrong?


Assuming $parentCategory is an existing CategoryModel (your error says that $parentCategory is not an object):

$childCategory = new CategoryModel();
$childCategory->groupId = 1;
$childCategory->newParentId = $parentCategory->id;
$childCategory->getContent()->title = $childCategoryName;


You can see how Craft does it for it's own categories in CategoriesController->saveCategory() and CategoriesService->saveCategory().

  • Works like a charm, thanks Brad! Curious though... why is it necessary to specify both newParentId and setParent? Couldn't one be extrapolated from the other?
    – Lindsey D
    Jun 25 '15 at 19:09
  • That particular chunk of code could probably use some refactoring.
    – Brad Bell
    Jun 25 '15 at 19:39
  • Updated: The relevant Craft code has changed, so the example has been simplified.
    – Lindsey D
    Nov 4 '16 at 16:54

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.