1

I have a custom-made Joomla 3 component used to create users in the frontend and adding some fields to another table. Now, I must change a bit this procedure: I must send an email to the new user with his username and password when he's registered.

In teory, this is really trivial. In my model, I should update the save() function, and after saving I send the email. And that's correct. But the problem is: how can I know that I'm creating a new user, and not updating and old user? I've been looking at Joomla3's documentation, but I don't know how to do this...

Can you help me, please?

  • you can check if id(assuming id is present and is primary key) present in instance of JTable. if exists that will update the record otherwise new row will inserted. – subashbasnet8 Jan 26 '15 at 13:15
4

I tried all of the possible ways and the absolute safest option is to add a dispatcher before the save functions and afterwards detach it.

Implement the save function that way in your model:

public function save ($data)
{
    $dispatcher = JDispatcher::getInstance();
    $eventHandler = new EventHandler($dispatcher, $this);

    $return = parent::save($data);

    $dispatcher->detach($eventHandler);

    return $return;
}

Add the following class to your model:

class EventHandler extends JEvent
{

    private $model = null;

    public function __construct (&$subject, $model)
    {
        parent::__construct($subject);

        $this->model = $model;
    }

    public function onContentBeforeSave ($context, $event, $isNew)
    {}

    public function onContentAfterSave ($context, $event, $isNew)
    {
        if ($context != 'com_dpcalendar.event' && $context != 'com_dpcalendar.form')
        {
            return;
        }

        if ($isNew)
        {
            // send mail
        }
    }

    public function onContentBeforeDelete ($context, $event)
    {}

    public function onContentAfterDelete ($context, $event)
    {}

    public function onContentChangeState ($context, $pks, $value)
    {}
}

I know this looks like a big overhead but it will keep you save.

  • It isn't possible to access the $isNew variable from inside the save() function? Because yes, it's a big overhead... – mHouses Jan 26 '15 at 14:44
3

If your model is inherited from JModelAdmin class then you can check for new record like this:

$isNew = $this->getState($this->getName() . '.new');

Otherwise you should check the data you saving - has it primary key set or not. See this part of code of JModelAdmin class.

  • I can't remember 100%, but this approach didn't work under every circumstances. – Laoneo Jan 26 '15 at 15:53

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.