I'm using this method so create new categories:
private function createCat($name){
$category = Mage::getModel( 'catalog/category' );
$category->setStoreId( 0 );
$category->setName( $name ); // The name of the category
$category->setUrlKey( strtolower($name) ); // The category's URL identifier
$category->setIsActive( 1 ); // Is it enabled?
$category->setIsAnchor( 0 );
// Display mode can be 'PRODUCTS_AND_PAGE', 'PAGE', or 'PRODUCTS'
$category->setDisplayMode( 'PRODUCTS' );
$category->setPath( '1/3' ); // Important you get this right.
$category->setPageTitle( $name );
$category->save();
return $category->getId();
}
After I know the ID that Magento has assigned to the category, I then call the following method in a loop to assign each category a parent category:
private function assignCat($id, $parent){
$category = Mage::getModel( 'catalog/category' )->load($id);
$category->setPath( '1/3/'.$parent.'/'.$id ); // Important you get this right.
$category->save();
return;
}
It doesn't however actually work. The first method creates the categories fine, but after running the second method, I can't even load the admin panel to show the categories.
What am I doing wrong?
EDIT:
I was sending the wrong id to the second method. It seems to have populated the database table catalog_category_entity correctly, but now the categories do not show correctly in the admin view. They are still showing as if the root category is the parent and in the database, the new parent is showing as having 0 children. Is there some kind of indexing that needs to take place?
EDIT: SOLUTION:
I've managed to find a solution in the mean time. To change the parent category, I needed to move the category under it using the built in category move() method:
private function assignCat($id, $parent){
$category = Mage::getModel( 'catalog/category' )->load($id);
Mage::unregister('category');
Mage::unregister('current_category');
Mage::register('category', $category);
Mage::register('current_category', $category);
$category->move($parent);
return;
}
You can just use setParentId()
:
$category->setParentId($parentCategoryId);
Alternatively you can use the Category Api Model to create the category:
$categoryData = array(
'name' => $name,
'url_key' => $urlKey,
'is_active' => '1',
);
$categoryApi = Mage::getModel('catalog/category_api_v2');
$categoryId = $categoryApi->create($parentCategoryId, $categoryData, $store)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With