3

While writing an import script, I need to create categories for the data, and am successfully accomplishing that with the below code. However, I can't determine how set the created_user_id column of the table.

The script is not logging in, but the created_user_id is always ignored, creating the category record with 0.

UPDATE Originally asked about path, but added ->rebuildPath()` - still no luck with the created_user_id

function createCategory( $title, $parent_id, $note=null ) {
    $table = JTable::getInstance('category');
    $data = array();
    $data['title'] = $title;
    $data['parent_id'] = $parent_id;
    $data['extension'] = 'com_content';
    $data['published'] = 1;
    $data['created_user_id'] = 123456;
    $table->setLocation($data['parent_id'], 'last-child');
    $table->bind($data);
    if ($table->check()) {
        $table->store();
        $table->rebuildPath($table->id);
        // Success
    } else {
        // Error
    }
}
2

To get around the problem, we used $app->login() before saving. This seemed to be the cleanest answer for our situation, as a great number of other category and content items were being added at the same time.

1

JTableCategory sets that property in the store function, so you will have to do a bit of a hack to get it to work.

You can either set the user that you want the id to be in the session:

$session = JFactory::getSession();
$user = JFactory::getUser($user_id);
$session->set('user', $user);

Literally just add that in place of this line: $data['created_user_id'] = 123456;. It should then automatically get set for the created_user_id.


Alternately, you would have to run the store twice like this:

$table->store();
$table->created_user_id = 123456;
$table->store();

The category table class only sets the created_user_id if it is a new object. The first store creates the record in the database and will store the id back in $table. Then you can reset the value that you want and store again. (Note that this way will then set the modified_time and modified_user_id incorrectly...)

1
  • Setting the $session user didn't seem to do the trick, and the double store might have worked, but we changed the code to use the $model->save() and it caused all the content plugins to be fired twice.
    – GDP
    Sep 19 '14 at 2: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.