how to add category programmatic?

For Joomla! 2.5 Coding related discussions, please use: http://groups.google.com/group/joomla-dev-general
Note: All 1.6, 1.7 and 3.5 releases have reached end of life and should be updated to 3.x.

Moderator: ooffick

Forum rules
Please use the mailing list here: http://groups.google.com/group/joomla-dev-general rather than this forum.
Locked
nevernet
Joomla! Apprentice
Joomla! Apprentice
Posts: 5
Joined: Tue Mar 31, 2009 2:13 am

how to add category programmatic?

Post by nevernet » Tue Jul 24, 2012 8:55 am

Hi,

i have another blog which was developed by DNN.
now, i want to transfer it Joomla.

i need to add category and article programmatic, but i also got an error when i try to add category:

i have created the test component, in the component entry file:

Code: Select all

defined('_JEXEC') or die;

// Include dependancies
jimport('joomla.application.component.controller');
//echo JPATH_ADMINISTRATOR;
require_once  JPATH_ADMINISTRATOR.DS.'components'.DS.'com_categories'.DS.'models'.DS.'category.php';

// Execute the task.
/* $controller	= JController::getInstance('Helloworld');
 $controller->execute(JRequest::getVar('task',''));
$controller->redirect(); */

//echo "Hello world";

//get categories
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('id, name');
$query->from('#__import_categories');
$db->setQuery($query, 0, 20);
$rows = (array) $db->loadObjectList();

$cateModel = new CategoriesModelCategory();

foreach($rows as $row){
    $data = array (
            'id' => 0,
            'parent_id' => '1',
            'extension' => 'com_content',
            'title' => $row->name,
            'alias' => '',
            'note' => '',
            'description' => '',
            'published' => '1',
            'access' => '1',
            'metadesc' => '',
            'metakey' => '',
            'created_user_id' => '0',
            'language' => '*',
            'rules' =>
            array (
                    'core.create' =>
                    array (
                    ),
                    'core.delete' =>
                    array (
                    ),
                    'core.edit' =>
                    array (
                    ),
                    'core.edit.state' =>
                    array (
                    ),
                    'core.edit.own' =>
                    array (
                    ),
            ),
            'params' =>
            array (
                    'category_layout' => '',
                    'image' => '',
            ),
            'metadata' =>
            array (
                    'author' => '',
                    'robots' => '',
            ),
    );
    
    $cateModel->save($data);
    
    echo $row->name . '<br />';
}
error is:
PHP Fatal error: Call to a member function setLocation() on a non-object in D:\CANADA\joomla-learning.testing.our-projects.info\administrator\components\com_categories\models\category.php on line 364
PHP Stack trace:
PHP 1. {main}() D:\CANADA\joomla-learning.testing.our-projects.info\index.php:0
PHP 2. JSite->dispatch() D:\CANADA\joomla-learning.testing.our-projects.info\index.php:42
PHP 3. JComponentHelper::renderComponent() D:\CANADA\joomla-learning.testing.our-projects.info\includes\application.php:197
PHP 4. JComponentHelper::executeComponent() D:\CANADA\joomla-learning.testing.our-projects.info\libraries\joomla\application\component\helper.php:351
PHP 5. require_once() D:\CANADA\joomla-learning.testing.our-projects.info\libraries\joomla\application\component\helper.php:383
PHP 6. CategoriesModelCategory->save() D:\CANADA\joomla-learning.testing.our-projects.info\components\com_helloworld\helloworld.php:116
the error is in file:
\administrator\components\com_categories\models\category.php
the error code is method "save":

Code: Select all

$table = $this->getTable();
the variable "$table" is false.

so , the problem is there:

Code: Select all

public function getTable($type = 'Category', $prefix = 'CategoriesTable', $config = array()) {
        $table = JTable::getInstance($type, $prefix, $config);
        //var_dump($table);
        return $table;
    }
in the JTable::getInstance method:
the $tableClass is : CategoriesTableCategory

but loaded file is : \libraries\joomla\database\table\category.php, in this file the Class name is : JTableCategory, but not CategoriesTableCategory.

the class "CategoriesTableCategory" is in file: /administrator/com_categories/tables/category.php.

can anyone help me where was wrong?

any ideas will be appreciated.

nevernet
Joomla! Apprentice
Joomla! Apprentice
Posts: 5
Joined: Tue Mar 31, 2009 2:13 am

Re: how to add category programmatic?

Post by nevernet » Wed Jul 25, 2012 1:01 am

any ideas?

User avatar
NFG
Joomla! Enthusiast
Joomla! Enthusiast
Posts: 108
Joined: Sat Sep 23, 2006 5:54 am

Re: how to add category programmatic?

Post by NFG » Wed Jul 25, 2012 1:34 pm

I am struggling with this problem too.
I have noticed that it was reported as a bug back in January.

With that in mind I started investigating a workaround by going straight to the table through JTable.

It creates the category, but does not correctly enter the parent_id and the level, and that causes the following error when listing categories in the admin:
Warning: str_repeat() [function.str-repeat]: Second argument has to be greater than or equal to 0 in ... /administrator/components/com_categories/views/categories/tmpl/default.php on line 110
Anyway, it is encouraging.

Code: Select all

		
		$basePath = JPATH_ADMINISTRATOR . '/components/com_categories';
		require_once $basePath . '/tables/category.php';
		$db =& JFactory::getDbo();
		$catmodel = new CategoriesTableCategory($db);
		$catData = array( 
			'id' => 0, 
			'parent_id' => 8, 
			'level' => 1, 
			'path' => 'categories/test-category', 
			'extension' => 'com_content', 
			'title' => 'Test category', 
			'alias' => 'test-category',
			'description' => 'It is just a test. Please try to relax.', 
			'published' => 1, 
			'language' => '*'
		);
		$status = $catmodel->save( $catData);

BramNL
Joomla! Fledgling
Joomla! Fledgling
Posts: 2
Joined: Sun Apr 27, 2014 4:57 pm

Re: how to add category programmatic?

Post by BramNL » Wed Nov 12, 2014 2:45 am

I wish to complete this topic for future reference by complimenting NFG for looking in a good direction. I myself was also unable to fix the parent_id/level-issue, but:

I found a complete working procedure in this gist: https://gist.github.com/mbabker/3211464 by Michael Babker (mbabker)

I have forked that one and modified it a bit so it applies to this thread better:
https://gist.github.com/brnl/9dfc85d541c9f774ec7d

And I'll also quote it here in case it ever went offline on GitHub:

Code: Select all

<?php

// Set the extension. For content categories, use 'com_content'
$extension = 'com_content';

// Set the title for the category
$title     = 'My Category';

// Type the description, this is also the 'body'. HTML allowed here.
$desc      = 'A category for my extension';

// Set the parent category. 1 is the root item.
$parent_id = 1;



// JTableCategory is autoloaded in J! 3.0, so...
if (version_compare(JVERSION, '3.0', 'lt'))
{
	JTable::addIncludePath(JPATH_PLATFORM . 'joomla/database/table');
}

// Initialize a new category
$category = JTable::getInstance('Category');
$category->extension = $extension;
$category->title = $title;
$category->description = $desc;
$category->published = 1;
$category->access = 1;
$category->params = '{"target":"","image":""}';
$category->metadata = '{"page_title":"","author":"","robots":""}';
$category->language = '*';

// Set the location in the tree
$category->setLocation($parent_id, 'last-child');

// Check to make sure our data is valid
if (!$category->check())
{
	JError::raiseNotice(500, $category->getError());
	return false;
}

// Now store the category
if (!$category->store(true))
{
	JError::raiseNotice(500, $category->getError());
	return false;
}

// Build the path for our category
$category->rebuildPath($category->id);
I hope this helps others too.

User avatar
rbuelund
Joomla! Guru
Joomla! Guru
Posts: 846
Joined: Sat Feb 10, 2007 9:07 pm
Location: Århus
Contact:

Re: how to add category programmatic?

Post by rbuelund » Sun Nov 12, 2017 3:22 pm

Could someone continue on this and show how to edit a category programatically ? And eventually delete a category ?
Ronny Buelund
Coordinator of the Danish Joomla Translation Team: http://danskjoomla.dk
Owner of http://ableit.dk


Locked

Return to “Joomla! 2.5 Coding”