user1201161
user1201161

Reputation:

Joomla: Can't make a plugin using onUserAfterSave work

Tried this half a dozen different ways and it's still not working. Joomla 1.7.3 on a local machine. The plugin does nothing, but it's not actually breaking anything - yet. As far as I can tell, the naming conventions are okay.

What I'm trying to do is insert a new row in a database table with the userid of a new user. The table has already been created and I checked the SQL query to make sure it worked.

<?php
// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

// Import library dependencies
jimport('joomla.plugin.plugin');

class plgUserCNPluginUpdate extends JPlugin 
{
    function onUserAfterSave ($user, $isnew, $success, $msg) 
    {
        if (!$success) 
        {
            return false;
        }
        if ($isnew) 
        {
            $db = JFactory::getDbo();
            $db->setQuery(
                'INSERT INTO `#__cnuser_cginfo`(`RecordID`,`UserID`) VALUES (NULL,'.(int) $user['id'].')'
            );
            $db->Query();
            return true;
        }
    }
}

Am I missing something obvious here? I've been looking around and any solution I try just doesn't work. It's in the right place and I can see it on the plugin manager screen. Hope someone can give me some advice on this.

Upvotes: 0

Views: 1688

Answers (1)

Craig
Craig

Reputation: 9330

Assuming this on Joomla 1.6/7/2.5... and if you have it in the right place i.e. /plugins/user/cnpluginupdate/ wrap your db code in some error checking like this:

try
{
    $db = JFactory::getDbo();
    $db->setQuery(
        'INSERT INTO `#__cnuser_cginfo`(`RecordID`,`UserID`)
         VALUES (NULL,'.(int) $user['id'].')'
    );

    if (!$db->query()) {
        throw new Exception($db->getErrorMsg());
    }        

    catch (JException $e)
    {
        $this->_subject->setError($e->getMessage());
        return false;
    }
}
  1. Currently you just return true no matter what happened so no error will be reported. Use a try as shown above to catch a possible error...

  2. Are you sure it's making it past the if (!$success) - normally you would check all the inputs prior to doing any work and you would only return a false if your code encountered an error.

eg.

function onUserAfterSave($data, $isNew, $result, $error)
{
    $userId = JArrayHelper::getValue($data, 'id', 0, 'int');

    if ($userId && $result && isset($data['profile']) && (count($data['profile'])))
    {
      // then 'try' your code here
    }

Upvotes: 1

Related Questions