7

After googling,etc. I've arrived at the below code to Add a new Category to Joomla so that all the plugin events, etc. get done.

$basePath = JPATH_ADMINISTRATOR.'/components/com_categories';
require_once $basePath.'/models/category.php';
$catmodel = new CategoriesModelCategory(array('table_path' => $basePath.'/tables'));

$myArrayOfData = array('id'=>'0','title'='my title'...);
$catmodel->save($myArrayOfData);

As it is now, I use the same code to update the record, but instead of a fresh copy of the data array to add, I use SQL to get the existing record as an array, then modify and save the same way.

This "works", but doesn't seem like the right way to do it, so I'm curious how to load the Model using the id of the Category , then use it's methods to change/save. I've tried following the code that executes when the Category Component does it, but too many things are going on for me to nail down how it's done.

3

Let's say you have the category ID which is stored in $id. You can instantiate the category model as you did it before:

$basePath = JPATH_ADMINISTRATOR . '/components/com_categories';
require_once $basePath . '/models/category.php';
$catModel = new CategoriesModelCategory(array('table_path' => $basePath . '/tables'));
$id = 11;

Now you have two methods:

Method 1 - Without JTable Object

$item = $catModel->getItem($id);
$catModel->save('id' => $id, 'parent_id' => $item->parent_id, 'title' => 'My New Title'); // parent_id should be defined otherwise a warning will be displayed

Method 2 - With JTable Object

$catTable = $catModel->getTable();
$catTable->load($id);
$catTable->title = 'My New Title';

$catTable->check();
$catTable->store();

Note

Only with the first method, onContentBeforeSave and onContentAfterSave events will be fired.

  • Aha...loading the table!...always so obvious after the fact, lol... – GDP Oct 4 '14 at 12:36
  • I'm getting non-object errors with this code. I've updated the question to incorporate your answer showing where. – GDP Oct 4 '14 at 13:30
  • @GDP, I modified my answer. Could you check it and tell us the result? – Farahmand Oct 4 '14 at 15:05
  • I get the error CategoriesTableCategory::bind(*NULL*), but your modified answer is using jTable, not the Model as I'm looking for....will this fire the plugin events like onContentAfterSave? – GDP Oct 4 '14 at 16:12
  • @GDP, I've edited my answer and it works now. The save method is used to bind form to data; I replaced it with check and store methods. Now the table is called from the model, so you have the category model in your hands, too. – Farahmand Oct 4 '14 at 17:34

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.