I'm trying to get the id of the parent category of another category. (I have the ID of the child Category.)
I've been trying to use Joomla's Category model, I successfully used the Article equivalent to get the Child Category ID from the Id of an article.
//article model
jimport('joomla.application.component.model');
$articlesModel = JModel::getInstance('ContentModelArticle');
$categoriesModel = JModel::getInstance('ContentModelCategory');
//Get Article Category id
$article = $articlesModel->getItem($art['id']);
$catid = $article->catid;
//Get Category Parent Category
$category = $categoriesModel->getItem($catid);
$parentID = $category->getParent();
echo "<pre>";
var_dump($parentID);
echo "</pre>";
But I keep getting an error saying that I'm trying to call a function of a non-object.
Can someone point out where I'm going wrong please? Thanks.
Edit: Should have mentioned this is all within the module file
Changed Tactic I found a different way to do this myself in the end: Now I'm querying the database for the information. It's useful in this case because I can grab the exact data I need.
$db =& JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('parent_id');
$query->from('#__categories');
$query->where("id = '$child_id'");
$db->setQuery($query);
//check if error
if ($db->getErrorNum()) {
echo $db->getErrorMsg();
exit;
}
$parent = $db->loadObjectList();
$parent_id = $parent['0']->parent_id;
If you want to load the ContentModelCategory
, you better use prefixing:
$categoriesModel = JModel::getInstance('Category','ContentModel');
However, I don't believe that this is the right model for you, as it gets its context from the request.
I can suggest 2 alternatives:
JCategories
instanceThis is the preferred method, used by the content component.
$article = $articlesModel->getItem($id);
$catid = $article->catid;
//Get Category Parent Category
$categoriesModel = JCategories::getInstance('content');
$category = $categoriesModel->get($catid);
$parent = $category->getParent();
if($parent){
$parentId = $parent->id;
echo "parentId: ".$parentId;
}
CategoriesModelCategory
This is the model used by com_categories.
$article = $articlesModel->getItem(5);
$catid = $article->catid;
//add the CategoriesModelCategory model include path
JModel::addIncludePath (JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_categories' . DS . 'models');
//add the table include path required by the model
JTable::addIncludePath (JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_categories' . DS . 'tables');
$categoriesModel = JModel::getInstance('Category','CategoriesModel');
$category = $categoriesModel->getItem($catid);
if($category){
$parentId = $category->parent_id;
echo "parentId: ".$parentId;
}